Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(liveman): add admin auth #215

Merged
merged 9 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 72 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ webrtc = { git = "https://github.com/webrtc-rs/webrtc", rev = "ae93e81" }

anyhow = "1.0"
clap = "4.5"
http = "1.1"
http-body = "1.0"
serde = "1"
tokio = "1.36"
tracing = "0.1"
Expand Down
10 changes: 3 additions & 7 deletions conf/live777.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,11 @@ urls = [
# WHIP/WHEP auth token
# Headers["Authorization"] = "Bearer {token}"
# [auth]
# JSON WEB TOKEN secret
# secret = "<jwt_secret>"
# static JWT token, superadmin, debuggger can use this token
# tokens = ["live777"]

# Not WHIP/WHEP standard
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic
# Headers["Authorization"] = "Basic {Base64.encode({username}:{password})}"
# [[auth.accounts]]
# username = "live777"
# password = "live777"

[log]
# Env: `LOG_LEVEL`
# Default: info
Expand Down
7 changes: 4 additions & 3 deletions conf/liveman.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
# WHIP/WHEP auth token
# Headers["Authorization"] = "Bearer {token}"
# [auth]
# JSON WEB TOKEN secret
# secret = "<jwt_secret>"
# static JWT token, superadmin, debuggger can use this token
# tokens = ["live777"]

# Not WHIP/WHEP standard
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic
# Headers["Authorization"] = "Basic {Base64.encode({username}:{password})}"
# Admin Dashboard Accounts
# [[auth.accounts]]
# username = "live777"
# password = "live777"
Expand Down
18 changes: 18 additions & 0 deletions libs/auth/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "auth"
edition.workspace = true

[lib]
crate-type = ["lib"]

[dependencies]
api = { path = "../api" }
anyhow = { workspace = true, features = ["backtrace"] }
http = { workspace = true }
http-body = { workspace = true }
axum = { version = "0.7" }
jsonwebtoken = "9.3"
serde = { workspace = true, features = ["serde_derive"] }

headers = "0.4.0"
tower-http = { version = "0.5.2", features = ["validate-request"] }
44 changes: 44 additions & 0 deletions libs/auth/src/access.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use axum::{extract::Request, http, middleware::Next, response::Response};
use http::method::Method;

use crate::{
claims::{Access, Claims},
ANY_ID,
};

pub async fn access_middleware(request: Request, next: Next) -> Response {
let ok = match request.extensions().get::<Claims>() {
Some(claims) => match (claims.id.clone(), request.method(), request.uri().path()) {
(id, &Method::GET, path) if path == api::path::streams(&id) => true,
(id, &Method::DELETE, path) if path == api::path::streams(&id) => {
Access::from(claims.mode).x
}
(id, &Method::POST, path) if path == api::path::whip(&id) => {
Access::from(claims.mode).w
}
(id, &Method::POST, path) if path == api::path::whep(&id) => {
Access::from(claims.mode).r
}
(id, &Method::POST, path) if path == api::path::cascade(&id) => {
Access::from(claims.mode).x
}
(id, _, _) if id == ANY_ID => true,
(id, &Method::POST, path) if path == "/token" && id == ANY_ID => {
Access::from(claims.mode).r
&& Access::from(claims.mode).w
&& Access::from(claims.mode).x
}
_ => false,
},
None => false,
};

if !ok {
return Response::builder()
.status(http::StatusCode::FORBIDDEN)
.body("Don't permission".into())
.unwrap();
}

next.run(request).await
}
109 changes: 109 additions & 0 deletions libs/auth/src/claims.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
use std::fmt::Display;

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Claims {
pub id: String,
pub exp: u64,
pub mode: Mode,
}

impl Display for Claims {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"id: {}\nexpire: {}, mode: {}",
self.id,
self.exp,
Access::from(self.mode)
)
}
}

/// Look like Linux File-system permissions
/// 4: read, allow use whep subscribe
/// 2: write, allow use whip publish
/// 1: execute, allow use manager this, example: destroy
type Mode = u8;

impl From<Mode> for Access {
fn from(mask: Mode) -> Access {
Access {
r: mask & 4 != 0,
w: mask & 2 != 0,
x: mask & 1 != 0,
}
}
}

pub struct Access {
pub r: bool,
pub w: bool,
pub x: bool,
}

impl From<Access> for Mode {
fn from(v: Access) -> Mode {
let r = if v.r { 4 } else { 0 };
let w = if v.w { 2 } else { 0 };
let x = if v.x { 1 } else { 0 };
r + w + x
}
}

impl Display for Access {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}{}{}",
if self.r { "r" } else { "-" },
if self.w { "w" } else { "-" },
if self.x { "x" } else { "-" },
)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_mode() {
let mut access = Access::from(7);
assert!(access.r);
assert!(access.w);
assert!(access.x);
assert_eq!(format!("{}", access), "rwx");

access = Access::from(6);
assert!(access.r);
assert!(access.w);
assert!(!access.x);
assert_eq!(format!("{}", access), "rw-");

access = Access::from(5);
assert!(access.r);
assert!(!access.w);
assert!(access.x);
assert_eq!(format!("{}", access), "r-x");

access = Access::from(4);
assert!(access.r);
assert!(!access.w);
assert!(!access.x);
assert_eq!(format!("{}", access), "r--");

access = Access::from(1);
assert!(!access.r);
assert!(!access.w);
assert!(access.x);
assert_eq!(format!("{}", access), "--x");

access = Access::from(0);
assert!(!access.r);
assert!(!access.w);
assert!(!access.x);
assert_eq!(format!("{}", access), "---");
}
}
Loading