Skip to content

Commit

Permalink
WIP:-
Browse files Browse the repository at this point in the history
  • Loading branch information
cupen committed Nov 11, 2024
1 parent 3108a38 commit a11b0f1
Show file tree
Hide file tree
Showing 4 changed files with 192 additions and 100 deletions.
39 changes: 39 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: Release

permissions:
contents: write

on:
push:
tags:
- v[0-9]+.*

jobs:
create-release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: taiki-e/create-gh-release-action@v1
with:
changelog: CHANGELOG.md
token: ${{ secrets.GITHUB_TOKEN }}

upload-assets:
needs: create-release
strategy:
matrix:
include:
- target: x86_64-unknown-linux-gnu
os: ubuntu-latest
- target: x86_64-pc-windows-msvc
os: windows-latest
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: taiki-e/upload-rust-binary-action@v1
with:
bin: fake-cdn
target: ${{ matrix.target }}
tar: unix
zip: windows
token: ${{ secrets.GITHUB_TOKEN }}
24 changes: 22 additions & 2 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use serde::{Serialize};
use structopt::StructOpt;

use std::sync::{Mutex, OnceLock};


#[derive(Debug, StructOpt)]
#[structopt(name = "args")]
Expand All @@ -26,7 +28,25 @@ pub enum Command {
},
}

pub fn get_args() -> &'static Args {
static ARGS: OnceLock<Args> = OnceLock::new();
return ARGS.get_or_init(|| parse_args());
}


pub fn get_args_token() -> &'static String {
let args = get_args();
match &args.command {
Command::Web { token, .. } => return token,
}
}

pub fn parse_args() -> Args {
return Args::from_args()
}
return Args::from_args();
}

// pub fn parse_args() -> &'static Mutex<Args> {
// // return Args::from_args()
// static ARGS: OnceLock<Mutex<Args>> = OnceLock::new();
// return ARGS.get_or_init(|| Mutex::new(Args::from_args()))
// }
23 changes: 18 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,22 @@ async fn upload(
}
debug!("[upload] {:?}", form);
let token = req.headers().get("Authorization");
match token {
Some(t) => {
info!("[upload] token: ...");
let token = cli::get_args_token();
if token.eq(t.to_str().unwrap()) {
info!("[upload] token: ok");
} else {
info!("[upload] token: invalid");
return HttpResponse::Unauthorized().body("Unauthorized");
}
}
None => {
info!("[upload] no token");
return HttpResponse::Unauthorized().body("Unauthorized");
}
}
info!("[upload] {} size: {}", fpath, form.file.size);
let full_path = PathBuf::from(UPLOAD_DIR).join(fpath.clone());

Expand Down Expand Up @@ -114,8 +130,8 @@ async fn status() -> impl Responder {
async fn main() -> std::io::Result<()> {
colog::init();

let args = cli::parse_args();
match args.command {
let args = cli::get_args();
match &args.command {
Command::Web { listen, dir, token } => {
let lis = listen
.parse::<SocketAddr>()
Expand All @@ -132,8 +148,5 @@ async fn main() -> std::io::Result<()> {
.run()
.await
}
_ => {
panic!("Invalid command");
}
}
}
206 changes: 113 additions & 93 deletions tests/upload_test.py
Original file line number Diff line number Diff line change
@@ -1,94 +1,114 @@
import requests
from pathlib import Path
import uuid

test_dir = Path(__file__).parent

def test_status():
url = 'http://localhost:9527/status'
resp = requests.get(url)
assert resp.status_code == 200


def test_upload_file():
id = str(uuid.uuid4())
url = f'http://localhost:9527/{id}/file-abc.txt'
files = {'file': open(__file__, 'rb')}
resp = requests.post(url, files=files)
assert resp.status_code == 200, resp.text

resp = requests.get(url)
assert resp.status_code == 200
assert resp.headers['Content-Type'] == 'text/plain; charset=utf-8'


def test_upload_html():
id = str(uuid.uuid4())
url = f'http://localhost:9527/{id}/index.html'
fpath = test_dir.joinpath('index.html')
with open(fpath, 'w') as f:
f.write('<h1>Hello, World!</h1>')
files = {'file': open(fpath, 'rb')}
resp = requests.post(url, files=files)
assert resp.status_code == 200, resp.text

resp = requests.get(url)
assert resp.status_code == 200
assert resp.text == '<h1>Hello, World!</h1>'
assert resp.headers['Content-Type'] == 'text/html; charset=utf-8'


def test_upload_html_override():
id = str(uuid.uuid4())
url = f'http://localhost:9527/override/index.html'
def do(content):
fpath = test_dir.joinpath('index.html')
with open(fpath, 'w') as f:
f.write(content)
files = {'file': open(fpath, 'rb')}
resp = requests.post(url, files=files)
assert resp.status_code == 200, resp.text

resp = requests.get(url)
assert resp.status_code == 200
assert resp.text == content
assert resp.headers['Content-Type'] == 'text/html; charset=utf-8'
pass

do(f'<h1>Hello, World!</h1>')
do(f'<h1>Hello, World!</h1> {id}')
do(f'<h1>Hello, World!</h1> {id} again')
pass

def create_file(name, content):
fpath = test_dir.joinpath(name)
with open(fpath, 'w') as f:
f.write(content)
return fpath

def test_upload_tar():
F = create_file
id = str(uuid.uuid4())
url = f'http://localhost:9527/tar/index.tar.gz'
url_files = [
'http://localhost:9527/tar/index.html',
'http://localhost:9527/tar/css/abc.css',
'http://localhost:9527/tar/js/abc.js',
]
# create a tar file
fpath = F('index.html', '<h1>Hello, World!</h1>')
import tarfile
with tarfile.open(fpath.with_suffix('.tar.gz'), 'w:gz') as tar:
tar.add(F("index.html", '<h1>Hello, World!</h1>'), arcname='index.html')
tar.add(F("abc.css", 'abc'), arcname='css/abc.css')
tar.add(F("abc.js", '{}'), arcname='js/abc.js')

files = {'file': open(fpath.with_suffix('.tar.gz'), 'rb')}
resp = requests.post(url, files=files)
assert resp.status_code == 200

for url in url_files:
resp = requests.get(url)
assert resp.status_code == 200
pass
import requests
from pathlib import Path
import uuid

TOKEN = "123456"
test_dir = Path(__file__).parent
base_url = 'http://localhost:9527'

class File:
@staticmethod
def upload(fpath, url_path, token=TOKEN):
files = {'file': open(fpath, 'rb')}
url = f'{base_url}/{url_path}'
if not token:
return requests.post(url, files=files)
headers = {'Authorization': token}
return requests.post(url, files=files, headers=headers)

@staticmethod
def download(url_path):
url = f'{base_url}/{url_path}'
return requests.get(url)

@staticmethod
def create(name, content):
fpath = test_dir.joinpath(name)
with open(fpath, 'w') as f:
f.write(content)
return fpath


def test_upload_token():
resp = File.upload(__file__, 'file-abc.txt', token='invalid token')
assert resp.status_code == 401, resp.text

resp = File.upload(__file__, 'file-abc.txt', token='')
assert resp.status_code == 401, resp.text


def test_status():
url = f'{base_url}/status'
resp = requests.get(url)
assert resp.status_code == 200
assert resp.json() == {'status': 'ok', 'version': '0.1.0'}


def test_upload_file():
id = str(uuid.uuid4())
resp = File.upload(__file__, f"{id}/file-abc.txt")
assert resp.status_code == 200, resp.text

resp = File.download(__file__, f"{id}/file-abc.txt")
assert resp.status_code == 200
assert resp.headers['Content-Type'] == 'text/plain; charset=utf-8'


def test_upload_html():
id = str(uuid.uuid4())
fpath = test_dir.joinpath('index.html')
with open(fpath, 'w') as f:
f.write('<h1>Hello, World!</h1>')
resp = File.upload(fpath, f"{id}/index.html")
assert resp.status_code == 200, resp.text

resp = File.download(f"{id}/index.html")
assert resp.status_code == 200
assert resp.text == '<h1>Hello, World!</h1>'
assert resp.headers['Content-Type'] == 'text/html; charset=utf-8'


def test_upload_html_override():
id = str(uuid.uuid4())
url = f'http://localhost:9527/override/index.html'
def do(content):
fpath = File.create('index.html', content)
resp = File.upload(fpath, f"{id}/index.html")
assert resp.status_code == 200, resp.text

resp = File.download(f"{id}/index.html")
assert resp.status_code == 200
assert resp.text == content
assert resp.headers['Content-Type'] == 'text/html; charset=utf-8'
pass

do(f'<h1>Hello, World!</h1>')
do(f'<h1>Hello, World!</h1> {id}')
do(f'<h1>Hello, World!</h1> {id} again')
pass


def test_upload_tar():
F = File.create
id = str(uuid.uuid4())
url_paths = [
'tar/index.html',
'tar/css/abc.css',
'tar/js/abc.js',
]
# create a tar file
fpath = F('index.html', '<h1>Hello, World!</h1>')
import tarfile
with tarfile.open(fpath.with_suffix('.tar.gz'), 'w:gz') as tar:
tar.add(F("index.html", '<h1>Hello, World!</h1>'), arcname='index.html')
tar.add(F("abc.css", 'abc'), arcname='css/abc.css')
tar.add(F("abc.js", '{}'), arcname='js/abc.js')
pass

resp = File.upload(fpath.with_suffix('.tar.gz'), f'tar/index.tar.gz')
assert resp.status_code == 200

for path in url_paths:
resp = File.download(path)
assert resp.status_code == 200
pass

0 comments on commit a11b0f1

Please sign in to comment.