Compare commits
51 Commits
ec81d3228b
...
feature/ag
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f5596dc69 | ||
|
|
96e7f36731 | ||
|
|
410328a2af | ||
|
|
9f122566d0 | ||
|
|
c65dc3af47 | ||
|
|
6f395ed1ae | ||
|
|
e6e85564e7 | ||
|
|
c7a090f78a | ||
|
|
8cc2775fe4 | ||
|
|
0b64538754 | ||
|
|
8009ca20ff | ||
|
|
7a5b9471e0 | ||
|
|
bb55e37b49 | ||
| 9a264a61ac | |||
|
|
0eafd6a264 | ||
|
|
c14af00c08 | ||
|
|
dce8203322 | ||
|
|
5cffb0a519 | ||
|
|
6e85bda13f | ||
|
|
7db23b01df | ||
|
|
61ecd91219 | ||
|
|
b823fe6281 | ||
|
|
7781878c2d | ||
|
|
4ca59d2bb6 | ||
| 8334da8cf1 | |||
|
|
dc7b70e039 | ||
|
|
873b4a9d3a | ||
|
|
596eb8faea | ||
|
|
0cd6e837fc | ||
|
|
be63fcbc37 | ||
|
|
3f252a8abd | ||
|
|
0740072a60 | ||
|
|
ff752985c6 | ||
|
|
feb5122843 | ||
|
|
0260a03e1b | ||
|
|
a88e4d7274 | ||
|
|
7d99a4852b | ||
|
|
e59e7ca4c8 | ||
|
|
b0b765b8fa | ||
|
|
d861e0cd7d | ||
|
|
b2b1fbaf65 | ||
|
|
d1491b8d19 | ||
|
|
85e8668e34 | ||
|
|
a0a9584a4d | ||
|
|
737797f6dd | ||
|
|
1d1a469fe0 | ||
|
|
227256e0e0 | ||
|
|
5060c84f28 | ||
|
|
903b7e6e5a | ||
| c8b7d6e09c | |||
|
|
507b5f0e49 |
6
.github/actions/setup-rust/action.yml
vendored
6
.github/actions/setup-rust/action.yml
vendored
@@ -22,7 +22,7 @@ runs:
|
|||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Cache cargo registry
|
- name: Cache cargo registry
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: ~/.cargo/registry
|
path: ~/.cargo/registry
|
||||||
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
||||||
@@ -30,7 +30,7 @@ runs:
|
|||||||
${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
|
||||||
- name: Cache cargo index
|
- name: Cache cargo index
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: ~/.cargo/index
|
path: ~/.cargo/index
|
||||||
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
|
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
|
||||||
@@ -51,7 +51,7 @@ runs:
|
|||||||
${{ runner.os }}-rustup-
|
${{ runner.os }}-rustup-
|
||||||
|
|
||||||
- name: Cache cargo build (target)
|
- name: Cache cargo build (target)
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: target
|
path: target
|
||||||
key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
|
key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
|||||||
41
.github/workflows/test.yml
vendored
41
.github/workflows/test.yml
vendored
@@ -12,11 +12,8 @@ on:
|
|||||||
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# setup is now handled by a composite action used by downstream jobs to keep
|
|
||||||
# the workflow DRY. The composite action performs checkout, cache restore and
|
|
||||||
# toolchain setup.
|
|
||||||
|
|
||||||
test:
|
test-crates:
|
||||||
needs: frontend-build
|
needs: frontend-build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -39,7 +36,7 @@ jobs:
|
|||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: cargo test --all-features
|
run: cargo test --all-features
|
||||||
|
|
||||||
lint:
|
lint-crates:
|
||||||
needs: frontend-build
|
needs: frontend-build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -67,6 +64,34 @@ jobs:
|
|||||||
- name: Check code formatting
|
- name: Check code formatting
|
||||||
run: cargo fmt --all -- --check
|
run: cargo fmt --all -- --check
|
||||||
|
|
||||||
|
lint-frontend:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 10
|
||||||
|
run_install: false
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: 'pnpm'
|
||||||
|
cache-dependency-path: pnpm-lock.yaml
|
||||||
|
|
||||||
|
- name: Install frontend dependencies
|
||||||
|
run: |
|
||||||
|
cd apps/frontend
|
||||||
|
pnpm install
|
||||||
|
|
||||||
|
- name: Run frontend linter
|
||||||
|
run: |
|
||||||
|
cd apps/frontend
|
||||||
|
pnpm lint
|
||||||
|
|
||||||
test-frontend:
|
test-frontend:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -86,7 +111,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 22
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
cache-dependency-path: apps/frontend/pnpm-lock.yaml
|
cache-dependency-path: pnpm-lock.yaml
|
||||||
|
|
||||||
- name: Install frontend dependencies
|
- name: Install frontend dependencies
|
||||||
run: |
|
run: |
|
||||||
@@ -114,12 +139,12 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 22
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
cache-dependency-path: apps/frontend/pnpm-lock.yaml
|
cache-dependency-path: pnpm-lock.yaml
|
||||||
|
|
||||||
- name: Install frontend dependencies
|
- name: Install frontend dependencies
|
||||||
run: |
|
run: |
|
||||||
cd apps/frontend
|
cd apps/frontend
|
||||||
pnpm install
|
pnpm install --frozen-lockfile
|
||||||
|
|
||||||
- name: Build frontend
|
- name: Build frontend
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
67
.github/workflows/verify.yml
vendored
67
.github/workflows/verify.yml
vendored
@@ -11,11 +11,8 @@ on:
|
|||||||
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# setup is now handled by a composite action used by downstream jobs to keep
|
|
||||||
# the workflow DRY. The composite action performs checkout, cache restore and
|
|
||||||
# toolchain setup.
|
|
||||||
|
|
||||||
verify-generated-code:
|
verify-generated-database-code:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
@@ -32,14 +29,62 @@ jobs:
|
|||||||
cargo run -- db:migrate_and_generate --output-path ../../public/database/src/generated/entities
|
cargo run -- db:migrate_and_generate --output-path ../../public/database/src/generated/entities
|
||||||
- name: Check for uncommitted changes in /generated/
|
- name: Check for uncommitted changes in /generated/
|
||||||
run: |
|
run: |
|
||||||
if [[ -n $(git status --porcelain | grep '^ M .*\/generated\/') ]]; then
|
if [[ -n $(git status --porcelain --untracked-files=all | grep '/generated/') ]]; then
|
||||||
echo "Generated code is not up to date. Please run the code generation locally and commit the changes."
|
echo "Generated code is not up to date. Please run the code generation locally and commit the changes."
|
||||||
git status --porcelain | grep '^ M .*\/generated\/'
|
git status --porcelain --untracked-files=all | grep '/generated/'
|
||||||
exit 1
|
exit 1
|
||||||
else
|
else
|
||||||
echo "Generated code is up to date."
|
echo "Generated code is up to date."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
verify-generated-agent-code:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- uses: actions/setup-java@v5
|
||||||
|
with:
|
||||||
|
distribution: 'temurin'
|
||||||
|
java-version: '21'
|
||||||
|
|
||||||
|
- name: Setup Rust, checkout and restore caches
|
||||||
|
uses: ./.github/actions/setup-rust
|
||||||
|
|
||||||
|
- name: Setup PNPM
|
||||||
|
uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 10
|
||||||
|
run_install: false
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: 'pnpm'
|
||||||
|
cache-dependency-path: pnpm-lock.yaml
|
||||||
|
|
||||||
|
- name: Install root dependencies
|
||||||
|
run: |
|
||||||
|
pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: generate agent client code
|
||||||
|
run: |
|
||||||
|
pnpm just generate-agent-client
|
||||||
|
|
||||||
|
|
||||||
|
- name: Check for uncommitted changes in agent client code
|
||||||
|
run: |
|
||||||
|
if [[ -n $(git status --porcelain --untracked-files=all | grep 'public/agent-client/') ]]; then
|
||||||
|
echo "Agent client code is not up to date. Please run the agent client code generation locally and commit the changes."
|
||||||
|
git status --porcelain --untracked-files=all | grep 'public/agent-client/'
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
echo "Agent client code is up to date."
|
||||||
|
fi
|
||||||
|
|
||||||
verify-openapi-spec:
|
verify-openapi-spec:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -99,9 +144,9 @@ jobs:
|
|||||||
- name: Check for uncommitted changes in swagger.json
|
- name: Check for uncommitted changes in swagger.json
|
||||||
if: steps.check_changes.outputs.changed == 'true'
|
if: steps.check_changes.outputs.changed == 'true'
|
||||||
run: |
|
run: |
|
||||||
if [[ -n $(git status --porcelain | grep '^ M apps/api/swagger.json') ]]; then
|
if [[ -n $(git status --porcelain --untracked-files=all | grep 'apps/api/swagger.json') ]]; then
|
||||||
echo "OpenAPI spec is not up to date. Please run the OpenAPI generation locally and commit the changes."
|
echo "OpenAPI spec is not up to date. Please run the OpenAPI generation locally and commit the changes."
|
||||||
git status --porcelain | grep '^ M apps/api/swagger.json'
|
git status --porcelain --untracked-files=all | grep 'apps/api/swagger.json'
|
||||||
exit 1
|
exit 1
|
||||||
else
|
else
|
||||||
echo "OpenAPI spec is up to date."
|
echo "OpenAPI spec is up to date."
|
||||||
@@ -165,7 +210,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 22
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
cache-dependency-path: apps/frontend/pnpm-lock.yaml
|
cache-dependency-path: pnpm-lock.yaml
|
||||||
|
|
||||||
- name: Install frontend dependencies
|
- name: Install frontend dependencies
|
||||||
if: steps.check_swagger_changes.outputs.changed == 'true'
|
if: steps.check_swagger_changes.outputs.changed == 'true'
|
||||||
@@ -182,9 +227,9 @@ jobs:
|
|||||||
- name: Check for uncommitted changes in frontend API client
|
- name: Check for uncommitted changes in frontend API client
|
||||||
if: steps.check_swagger_changes.outputs.changed == 'true'
|
if: steps.check_swagger_changes.outputs.changed == 'true'
|
||||||
run: |
|
run: |
|
||||||
if [[ -n $(git status --porcelain | grep '^ M apps/frontend/app/generated/api-client') ]]; then
|
if [[ -n $(git status --porcelain --untracked-files=all | grep 'apps/frontend/app/generated/api-client') ]]; then
|
||||||
echo "Frontend API client is not up to date. Please run the API client generation locally and commit the changes."
|
echo "Frontend API client is not up to date. Please run the API client generation locally and commit the changes."
|
||||||
git status --porcelain | grep '^ M apps/frontend/app/generated/api-client'
|
git status --porcelain --untracked-files=all | grep 'apps/frontend/app/generated/api-client'
|
||||||
exit 1
|
exit 1
|
||||||
else
|
else
|
||||||
echo "Frontend API client is up to date."
|
echo "Frontend API client is up to date."
|
||||||
|
|||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -27,3 +27,5 @@ target
|
|||||||
.env.generated
|
.env.generated
|
||||||
|
|
||||||
generated-config.yaml
|
generated-config.yaml
|
||||||
|
|
||||||
|
node_modules/
|
||||||
|
|||||||
997
Cargo.lock
generated
997
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,8 @@ members = [
|
|||||||
"apps/api",
|
"apps/api",
|
||||||
"apps/container",
|
"apps/container",
|
||||||
"apps/cli",
|
"apps/cli",
|
||||||
|
"apps/agent",
|
||||||
|
"public/agent-client",
|
||||||
"public/shared",
|
"public/shared",
|
||||||
"public/database",
|
"public/database",
|
||||||
"public/migration"
|
"public/migration"
|
||||||
|
|||||||
1
apps/agent/.gitignore
vendored
Normal file
1
apps/agent/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
*.sock
|
||||||
16
apps/agent/Cargo.toml
Normal file
16
apps/agent/Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
name = "yanpm-agent"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
axum = { version = "0.8.7", features = ["form", "http1", "json", "matched-path", "original-uri", "query", "tokio", "tower-log", "tracing", "macros"] }
|
||||||
|
tokio = { version = "1", features = ["fs", "io-util", "io-std", "macros", "net", "parking_lot", "process", "rt", "rt-multi-thread", "signal", "sync", "time", "tracing"] }
|
||||||
|
tracing = { version = "0.1.41", features = ["std", "attributes"] }
|
||||||
|
tracing-subscriber = { version = "0.3.20", features = ["smallvec", "fmt", "ansi", "tracing-log", "std", "json", "serde", "serde_json", "time", "tracing"] }
|
||||||
|
serde_json = { version = "1.0.145", features = ["std"] }
|
||||||
|
serde = { version = "1.0.228", features = ["std", "derive"] }
|
||||||
|
tokio-cron-scheduler = { version = "0.15.1", features = ["signal"] }
|
||||||
|
clap = { version = "4", features = ["derive", "env"] }
|
||||||
|
nix = { version = "0.30.1", features = ["user", "fs"] }
|
||||||
|
utoipa = { version = "5.4.0", features = ["macros", "axum_extras", "chrono", "decimal", "uuid", "time", "openapi_extensions"] }
|
||||||
56
apps/agent/Dockerfile
Normal file
56
apps/agent/Dockerfile
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
FROM rust:1.92-alpine3.23 AS builder
|
||||||
|
|
||||||
|
# Install build deps and binutils (for strip)
|
||||||
|
RUN apk add --no-cache build-base musl-dev openssl-dev pkgconfig ca-certificates curl binutils
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy manifest first to leverage Docker layer caching for dependencies
|
||||||
|
COPY ./Cargo.toml ./
|
||||||
|
RUN cargo fetch --locked || true
|
||||||
|
|
||||||
|
COPY ./src ./src
|
||||||
|
|
||||||
|
# Build the release binary and strip it to reduce size
|
||||||
|
RUN cargo build --release --bin yanpm-agent && \
|
||||||
|
strip target/release/yanpm-agent || true
|
||||||
|
|
||||||
|
FROM nginx:mainline-alpine3.23 AS base
|
||||||
|
|
||||||
|
# Expose typical HTTP ports used by nginx
|
||||||
|
EXPOSE 80 443
|
||||||
|
|
||||||
|
ENV S6_KEEP_ENV=1
|
||||||
|
ENV YANPM_AGENT_SOCK=/var/run/yanpm/yanpm-agent.sock
|
||||||
|
ENV YANPM_NGINX_CONFIG_DIR=/etc/nginx/conf.d
|
||||||
|
ENV YANPM_AGENT_SOCK_PERM=660
|
||||||
|
ENV YANPM_AGENT_SOCK_GID=""
|
||||||
|
ENV YANPM_AGENT_UID=1000
|
||||||
|
ENV YANPM_AGENT_GID=1000
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install ca-certificates for TLS and minimal tools
|
||||||
|
RUN apk add --no-cache ca-certificates curl
|
||||||
|
|
||||||
|
# Install s6-overlay
|
||||||
|
ENV S6_OVERLAY_VERSION=v3.2.1.0
|
||||||
|
ADD https://github.com/just-containers/s6-overlay/releases/download/${S6_OVERLAY_VERSION}/s6-overlay-noarch.tar.xz /tmp
|
||||||
|
RUN tar -C / -Jxpf /tmp/s6-overlay-noarch.tar.xz && rm /tmp/s6-overlay-noarch.tar.xz
|
||||||
|
ADD https://github.com/just-containers/s6-overlay/releases/download/${S6_OVERLAY_VERSION}/s6-overlay-x86_64.tar.xz /tmp/s6-overlay.tar.xz
|
||||||
|
RUN tar -C / -Jxpf /tmp/s6-overlay.tar.xz && rm /tmp/s6-overlay.tar.xz
|
||||||
|
|
||||||
|
# Runtime user creation handled by s6 cont-init (see /etc/cont-init.d)
|
||||||
|
# create directory for yanpm agent socket; ownership will be fixed at container start
|
||||||
|
RUN mkdir -p /var/run/yanpm
|
||||||
|
|
||||||
|
# Copy s6 service definitions (created in repo under s6/) into image
|
||||||
|
COPY ./docker/s6/services.d /etc/services.d
|
||||||
|
COPY ./docker/s6/cont-init.d /etc/cont-init.d
|
||||||
|
RUN chmod +x /etc/services.d/*/run && chmod +x /etc/cont-init.d/*
|
||||||
|
|
||||||
|
COPY --from=builder /app/target/release/yanpm-agent ./yanpm-agent
|
||||||
|
|
||||||
|
RUN chmod +x /app/yanpm-agent
|
||||||
|
|
||||||
|
# s6-overlay provides /init as the init process
|
||||||
|
ENTRYPOINT ["/init"]
|
||||||
19
apps/agent/doc/README.md
Normal file
19
apps/agent/doc/README.md
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
# yanpm-agent Documentation
|
||||||
|
|
||||||
|
This directory contains in-depth documentation for the yanpm agent daemon (the binary built from `apps/agent`). The agent exposes a unix-socket HTTP API for writing nginx configuration fragments, validating them, and reloading nginx safely.
|
||||||
|
|
||||||
|
Docs included:
|
||||||
|
|
||||||
|
- `architecture.md` — Detailed explanation of the program flow and components.
|
||||||
|
- `configuration.md` — CLI flags, environment variables, defaults, and permission handling.
|
||||||
|
- `usage.md` — How to run the agent, curl examples, and systemd/docker hints.
|
||||||
|
- `api.md` — HTTP API endpoints, request and response schemas, examples.
|
||||||
|
- `deployment.md` — Deployment considerations, permissions, and systemd socket/unit examples.
|
||||||
|
- `troubleshooting.md` — Common errors and solutions.
|
||||||
|
|
||||||
|
For implementation details, see the source in `apps/agent/src` (notably `main.rs`, `routes.rs`, and the `commands/` submodule).
|
||||||
|
|
||||||
|
Integration notes
|
||||||
|
|
||||||
|
- The agent is intended to run as a companion agent for the API service in `apps/api`. The API service calls the agent over the unix-domain socket to write nginx fragments, validate them, and trigger reloads.
|
||||||
|
- A production Docker image is provided by `apps/agent/Dockerfile`. That Dockerfile packages nginx + the `yanpm-agent` binary and s6-overlay service scripts so a single container can run nginx and the agent alongside each other.
|
||||||
68
apps/agent/doc/api.md
Normal file
68
apps/agent/doc/api.md
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
# HTTP API Reference
|
||||||
|
|
||||||
|
Base: HTTP over a unix-domain socket. Example using curl: `curl --unix-socket /path/to/socket -X POST http://localhost/<path>`
|
||||||
|
|
||||||
|
1) GET /status
|
||||||
|
|
||||||
|
- Response: 200 OK
|
||||||
|
- Body: JSON `{ "ok": true }`
|
||||||
|
|
||||||
|
2) POST /validate
|
||||||
|
|
||||||
|
- Request JSON:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"config_name": "example",
|
||||||
|
"timestamp": 1234567890
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Behavior: validates the fragment file named by `config_name` and `timestamp` under the agent's internal subdirectory inside the configured nginx config directory. Delegates to `ValidateCommand::validate`.
|
||||||
|
- Success: 200 OK, body is `[rc, output]` tuple serialized as JSON (actual shape is `(i32, String)` returned from the command; examine responses for exact formatting).
|
||||||
|
- Error cases:
|
||||||
|
- 400 Bad Request: invalid or malformed JSON
|
||||||
|
- 500 Internal Server Error: validation error or missing fragment file
|
||||||
|
|
||||||
|
- Request JSON:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"config_name": "example",
|
||||||
|
"timestamp": 1234567890
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Behavior: validates the fragment file named by `config_name` and `timestamp` under the agent's internal subdirectory inside the configured nginx config directory. Delegates to `ValidateCommand::validate`.
|
||||||
|
- Success: 200 OK, body is a JSON array `[rc, output]` where `rc` is the integer return code and `output` is the combined stdout/stderr string from the validation command (the command returns an `(i32, String)` tuple).
|
||||||
|
- Error cases:
|
||||||
|
- 400 Bad Request: invalid or malformed JSON
|
||||||
|
- 500 Internal Server Error: validation error or missing fragment file
|
||||||
|
|
||||||
|
3) POST /validate_and_reload
|
||||||
|
|
||||||
|
- Request JSON same as `/validate`.
|
||||||
|
- Behavior: runs validation and, on success, attempts to reload nginx. Returns an object with `rc` and `ro` (return code and combined stdout/stderr output).
|
||||||
|
- Success: 200 OK with body: `{ "rc": <int>, "ro": "<output>" }`
|
||||||
|
- Errors: 400 for malformed JSON, 500 if the validate-and-reload command fails (body presents error text).
|
||||||
|
|
||||||
|
4) POST /write_config
|
||||||
|
|
||||||
|
- Request JSON:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"config_name": "example",
|
||||||
|
"timestamp": 1234567890,
|
||||||
|
"content": "server { ... }"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Behavior: writes the provided `content` into an agent-managed fragment file named from `config_name` and `timestamp` in the internal subdirectory under `nginx_config_dir`.
|
||||||
|
- Success: 200 OK with empty body
|
||||||
|
- Error: 400 for malformed JSON, 500 if writing the file fails
|
||||||
|
|
||||||
|
Notes
|
||||||
|
|
||||||
|
- The agent expects callers to choose a `config_name` and `timestamp` that together form a unique filename. The concrete filename encoding is performed by `commands::run::to_file_name` in source.
|
||||||
|
- On validation failures the returned output often contains the full `nginx -t` output; inspect `ro` or the returned JSON error messages.
|
||||||
34
apps/agent/doc/architecture.md
Normal file
34
apps/agent/doc/architecture.md
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# Architecture and Runtime Flow
|
||||||
|
|
||||||
|
Overview
|
||||||
|
|
||||||
|
- The agent is an async HTTP server (axum) listening on a Unix domain socket and exposes a small JSON API to manage nginx configuration fragments.
|
||||||
|
- Core lifecycle is implemented in `apps/agent/src/main.rs`:
|
||||||
|
- parse CLI args and environment variables
|
||||||
|
- ensure the socket path and directory exist and have permissive but secure defaults
|
||||||
|
- bind a `tokio::net::UnixListener` to the socket
|
||||||
|
- create an `NginxService` (shared state) and an in-process cron `JobScheduler`
|
||||||
|
- mount axum routes (`/status`, `/validate`, `/validate_and_reload`, `/write_config`) and serve HTTP over the Unix socket
|
||||||
|
|
||||||
|
Key components
|
||||||
|
|
||||||
|
- `main.rs` — Bootstrapping, argument handling, socket setup and permission handling, scheduler start, and axum server startup.
|
||||||
|
- `routes.rs` — axum handlers for the HTTP API. It deserializes JSON payloads and delegates to `NginxService` methods. Handlers return appropriate HTTP status codes and JSON on error or success.
|
||||||
|
- `commands/` — Implementation of lower-level actions (writing fragment files, running `nginx -t`, validating, reloads). The `validate.rs` command contains sophisticated behavior to handle permission-limited environments by:
|
||||||
|
- creating wrapper nginx configs that include a single fragment
|
||||||
|
- trying `nginx -t` directly, attempting a privileged wrapper via `sudo` if available, and finally passing a writable PID override via `-g pid ...;` to avoid permission failures
|
||||||
|
|
||||||
|
Concurrency and state
|
||||||
|
|
||||||
|
- A single shared `NginxService` instance is stored in axum `State` and cloned into handlers; it holds the scheduler and the configured nginx config directory path.
|
||||||
|
- The JobScheduler is created with `tokio_cron_scheduler::JobScheduler` and started before serving requests.
|
||||||
|
|
||||||
|
Error handling and best-effort behavior
|
||||||
|
|
||||||
|
- Socket permission changes, GID changes, and directory creations are best-effort and log warnings on failure rather than failing hard.
|
||||||
|
- Most command failures are converted into JSON errors with appropriate HTTP status codes so callers can inspect command output.
|
||||||
|
|
||||||
|
Integration and packaging
|
||||||
|
|
||||||
|
- The agent is intended to run as a companion to the API server in `apps/api`. The API calls the agent over the unix socket to write fragments, validate them, and trigger reloads.
|
||||||
|
- `apps/agent/Dockerfile` builds a runtime image that includes `nginx` and the `yanpm-agent` binary (the Dockerfile uses s6-overlay to run multiple services). This image is suitable for deployments that prefer nginx and the agent colocated in a single container.
|
||||||
27
apps/agent/doc/configuration.md
Normal file
27
apps/agent/doc/configuration.md
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# Configuration and Environment
|
||||||
|
|
||||||
|
CLI flags and environment variables
|
||||||
|
|
||||||
|
- `--sock` / `YANPM_AGENT_SOCK` (default: `./yanpm-agent.sock`)
|
||||||
|
- Path to the Unix socket file the agent will bind to.
|
||||||
|
- If the socket directory does not exist the agent attempts to create it and set mode `0770`.
|
||||||
|
|
||||||
|
- `--nginx-config-dir` / `YANPM_NGINX_CONFIG_DIR` (default: `/etc/nginx/conf.d`)
|
||||||
|
- Directory where nginx fragments are written. The agent writes fragments into a subdirectory named by the agent (internal use).
|
||||||
|
|
||||||
|
- `--sock-perm` / `YANPM_AGENT_SOCK_PERM` (default: `660`)
|
||||||
|
- A 3-digit octal permission string applied to the socket file (best-effort). The program validates this is a 3-digit octal string.
|
||||||
|
- If the final digit is greater than `0` a warning is logged because that allows "others" access.
|
||||||
|
|
||||||
|
- `--sock-gid` / `YANPM_AGENT_SOCK_GID` (default: current user's primary group)
|
||||||
|
- GID to set on the socket file (best-effort).
|
||||||
|
|
||||||
|
Validation rules and behavior
|
||||||
|
|
||||||
|
- `sock_perm` must be exactly 3 octal digits (characters 0-7). The agent rejects invalid values at startup.
|
||||||
|
- When an existing path exists at the socket location the agent verifies it is a unix socket; if so it removes it before binding. If the path exists and is not a socket, startup fails.
|
||||||
|
- Setting permissions (`set_permissions`) and changing GID (`chown`) are attempted but non-fatal: failures are logged as warnings and the agent continues.
|
||||||
|
|
||||||
|
Notes about nginx config directory
|
||||||
|
|
||||||
|
- The agent writes fragments into a subdirectory (internal) of the configured `nginx_config_dir`. Ensure nginx is configured to include that subdirectory so fragments are picked up, or use `write_config` then trigger a reload.
|
||||||
62
apps/agent/doc/deployment.md
Normal file
62
apps/agent/doc/deployment.md
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
# Deployment and Permissions
|
||||||
|
|
||||||
|
Socket location and permissions
|
||||||
|
|
||||||
|
- The agent binds a unix socket at the path given by `--sock` or `YANPM_AGENT_SOCK`. The agent will:
|
||||||
|
- create the parent directory (best-effort) and attempt to set its permissions to `0770`
|
||||||
|
- remove an existing socket file if it is a socket, or fail if the path exists and is not a socket
|
||||||
|
- apply the `sock_perm` (3-digit octal) to the socket file and optionally change its GID to `sock_gid`
|
||||||
|
|
||||||
|
Systemd socket/unit example
|
||||||
|
|
||||||
|
Create a `yanpm-agent.socket` unit that creates and owns the unix socket, and a `yanpm-agent.service` that runs the agent. Ensure the socket path used by systemd matches `--sock`.
|
||||||
|
|
||||||
|
Docker / container notes
|
||||||
|
|
||||||
|
- If running the agent inside a container and writing to host nginx config, bind-mount the host nginx config directory into the container at the path provided to `--nginx-config-dir`.
|
||||||
|
- Consider running the agent as a user with permission to write the nginx config directory or use a shared group and `sock_gid` so clients can access the socket.
|
||||||
|
- The repository provides a runtime image built by `apps/agent/Dockerfile` which packages `nginx` together with the `yanpm-agent` binary and s6-overlay service scripts. This image runs nginx and the agent in one container which is useful when the agent is acting as the runtime companion for the API (`apps/api`).
|
||||||
|
|
||||||
|
Privilege escalation for validation
|
||||||
|
|
||||||
|
- In many systems `nginx -t` may fail due to inability to access `/run/nginx.pid` or other privileged files. The agent attempts a best-effort sequence:
|
||||||
|
|
||||||
|
1. Run `nginx -t` directly.
|
||||||
|
2. If that fails with permission errors, try a privileged wrapper (e.g. `/usr/local/sbin/yanpm-nginx-validate` or `yanpm-nginx-validate-file`) via `sudo -n`.
|
||||||
|
3. If wrapper is unavailable or fails, retry `nginx -t` with a writable PID override via `-g 'pid /tmp/yanpm-validate-<pid>.pid;'`.
|
||||||
|
|
||||||
|
Security considerations
|
||||||
|
|
||||||
|
- Avoid setting `sock_perm` to allow world access unless explicitly intended.
|
||||||
|
- Prefer controlling socket group membership via `sock_gid` rather than making the socket world-writable.
|
||||||
|
|
||||||
|
s6 init scripts, wrappers and sudoers (runtime)
|
||||||
|
|
||||||
|
- Purpose: The image built by `apps/agent/Dockerfile` uses `s6-overlay` as PID 1 (the Dockerfile sets `ENTRYPOINT ["/init"]`). The repository includes `docker/s6/cont-init.d` scripts that run at container startup (one-shot) and `docker/s6/services.d` entries to run long-lived services (nginx and the agent). The cont-init scripts prepare runtime users, permissions, and helper wrappers the agent uses for privileged operations.
|
||||||
|
|
||||||
|
- Key cont-init scripts (in the repo):
|
||||||
|
- `docker/s6/cont-init.d/10-create-app-user` — ensures the `yanpm-agent` user and group exist (honoring `YANPM_AGENT_UID`, `YANPM_AGENT_GID`, and `YANPM_AGENT_SOCK_GID`), adds the user to the `nginx` group, and attempts to chown runtime directories like `/var/run/yanpm` and `/app/yanpm-agent` (logs warnings if chown fails for bind mounts or rootless containers).
|
||||||
|
- `docker/s6/cont-init.d/20-install-reload-wrapper` — installs three helper wrappers and a sudoers entry so the `yanpm-agent` user can perform narrowly-scoped privileged operations without a password.
|
||||||
|
|
||||||
|
- Wrapper scripts installed by `20-install-reload-wrapper`:
|
||||||
|
- `/usr/local/sbin/yanpm-nginx-reload` — runs `nginx -c /etc/nginx/nginx.conf -s reload` (used for reloading the running nginx master process).
|
||||||
|
- `/usr/local/sbin/yanpm-nginx-validate` — runs `nginx -c /etc/nginx/nginx.conf -t` (validates the main nginx config).
|
||||||
|
- `/usr/local/sbin/yanpm-nginx-validate-file` — securely validates a single nginx config file: it resolves the absolute path, ensures the target is a regular file (not a symlink), checks the file is owned by the `yanpm-agent` user, enforces it's not world-writable, then runs `nginx -c <file> -t`. This defends against symlink and race attacks when an unprivileged agent requests privileged validation.
|
||||||
|
|
||||||
|
- Sudoers entry:
|
||||||
|
- The init script writes `/etc/sudoers.d/yanpm-agent` with a rule allowing the configured agent user (default `yanpm-agent`) to run only the three wrappers with `NOPASSWD`. This gives the agent a limited, auditable privilege escalation surface; the agent code attempts to use these wrappers via `sudo -n` before falling back to less privileged strategies.
|
||||||
|
|
||||||
|
- Relevant environment variables (settable in the Dockerfile or at runtime):
|
||||||
|
- `YANPM_AGENT_SOCK` — unix socket path (default set in Dockerfile: `/var/run/yanpm/yanpm-agent.sock`).
|
||||||
|
- `YANPM_NGINX_CONFIG_DIR` — nginx config dir (default `/etc/nginx/conf.d`).
|
||||||
|
- `YANPM_AGENT_SOCK_PERM` — socket permissions (octal string, default `660`).
|
||||||
|
- `YANPM_AGENT_SOCK_GID` — desired GID for the socket (optional).
|
||||||
|
- `YANPM_AGENT_UID`, `YANPM_AGENT_GID` — runtime UID/GID used to create the `yanpm-agent` user in the container.
|
||||||
|
|
||||||
|
- How the agent uses these runtime helpers:
|
||||||
|
- `ValidateCommand` and `ReloadCommand` in the agent code try `nginx` operations directly; when permission problems occur they attempt the privileged wrappers via `sudo -n /usr/local/sbin/yanpm-nginx-validate` or `...-validate-file` and `...-reload`. The cont-init script's wrappers plus the sudoers entry implement that intended secure upgrade path.
|
||||||
|
|
||||||
|
- Notes and recommendations:
|
||||||
|
- The `validate-file` wrapper performs ownership and permission checks; ensure written fragments are created by the `yanpm-agent` user (the agent writes files as that user when running inside the container due to `10-create-app-user`).
|
||||||
|
- The cont-init scripts attempt to install `sudo` if missing; in minimal images you may prefer providing `sudo` at build time to avoid runtime installation attempts.
|
||||||
|
- If you bind-mount host directories (e.g., `/etc/nginx/conf.d`) into the container, ensure ownership and permissions are compatible with the agent user and `YANPM_AGENT_SOCK_GID` so the socket and files are accessible as intended.
|
||||||
27
apps/agent/doc/troubleshooting.md
Normal file
27
apps/agent/doc/troubleshooting.md
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# Troubleshooting
|
||||||
|
|
||||||
|
Common issues and how to resolve them
|
||||||
|
|
||||||
|
- Socket path exists but is not a socket
|
||||||
|
- Symptom: startup fails with an error that the socket path exists and is not a socket.
|
||||||
|
- Fix: remove the file at the socket path or choose a different `--sock` path.
|
||||||
|
|
||||||
|
- Permission denied on socket directory or socket
|
||||||
|
- Symptom: socket creation or permission setting logs warnings; clients cannot connect.
|
||||||
|
- Fix: ensure the socket directory exists and has correct ownership/group and that `sock_perm` and `sock_gid` are configured appropriately. Consider using `chown`/`chmod` from a privileged context.
|
||||||
|
|
||||||
|
- `nginx -t` fails with `/run/nginx.pid: Permission denied`
|
||||||
|
- Symptom: validation fails; output contains permission denied for `/run/nginx.pid`.
|
||||||
|
- Fixes (tried by the agent):
|
||||||
|
1. If available, provide a privileged validation wrapper (e.g. `/usr/local/sbin/yanpm-nginx-validate`) that runs `nginx -t` with appropriate privileges.
|
||||||
|
2. Ensure the agent-runner has permission to read the main nginx configuration and `/run/nginx.pid` or allow the agent to use a writable PID override.
|
||||||
|
|
||||||
|
- Fragment file not found during validation
|
||||||
|
- Symptom: validate returns 500 with message `Config file not found`.
|
||||||
|
- Fix: make sure the fragment has been written via `/write_config` to the agent's internal subdirectory under `NGINX_CONFIG_DIR`, using the same `config_name` and `timestamp` as the validate call.
|
||||||
|
|
||||||
|
- Wrapper or sudo not available
|
||||||
|
- Symptom: attempts to run `sudo -n /usr/local/sbin/yanpm-nginx-validate` fail.
|
||||||
|
- Fix: install a wrapper script that allows unprivileged `sudo -n` validation or configure proper permissions on nginx state files.
|
||||||
|
|
||||||
|
If none of the above solves the problem, collect the logs produced by the agent (it uses `tracing`/`tracing_subscriber`) and include the exact command outputs from the validation steps when asking for help.
|
||||||
61
apps/agent/doc/usage.md
Normal file
61
apps/agent/doc/usage.md
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
# Usage and Examples
|
||||||
|
|
||||||
|
Running locally (development)
|
||||||
|
|
||||||
|
1. Build the agent (from repository root):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo build -p agent
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Run the agent with defaults (socket in current directory):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./target/debug/yanpm-agent
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Run with explicit socket and nginx config directory:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./target/debug/yanpm-agent --sock /run/yanpm/yanpm-agent.sock --nginx-config-dir /etc/nginx/conf.d
|
||||||
|
```
|
||||||
|
|
||||||
|
HTTP over unix-socket examples (using `socat` / `curl` helper)
|
||||||
|
|
||||||
|
If you want to call the API from the shell, you can use `socat` to convert the unix socket to an HTTP stream, or use tools that support unix sockets directly (e.g. `curl --unix-socket`). Examples below use `curl --unix-socket`.
|
||||||
|
|
||||||
|
Validate a fragment by name and timestamp:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl --unix-socket ./yanpm-agent.sock -X POST http://localhost/validate \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"config_name":"example","timestamp":1234567890}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Validate and reload (returns `rc` and `ro`):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl --unix-socket ./yanpm-agent.sock -X POST http://localhost/validate_and_reload \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"config_name":"example","timestamp":1234567890}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Write a fragment (create or update):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl --unix-socket ./yanpm-agent.sock -X POST http://localhost/write_config \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"config_name":"example","timestamp":1234567890,"content":"server { listen 80; server_name example.local; }"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Status endpoint (health)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl --unix-socket ./yanpm-agent.sock http://localhost/status
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes
|
||||||
|
|
||||||
|
- Use the `config_name` and `timestamp` fields consistently: `timestamp` is typically a monotonic update ID from the caller ensuring unique file names.
|
||||||
|
- When running in containers, mount the host nginx config dir if you want the agent to write directly to host nginx configuration.
|
||||||
|
- The repository includes a runtime Docker image built by `apps/agent/Dockerfile` which bundles `nginx` and the `yanpm-agent` binary (via s6-overlay). Use that image when you want nginx and the agent colocated (the agent is intended as a runtime companion to `apps/api`).
|
||||||
58
apps/agent/docker/s6/cont-init.d/10-create-app-user
Normal file
58
apps/agent/docker/s6/cont-init.d/10-create-app-user
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
YANPM_AGENT_UID="${YANPM_AGENT_UID:-1000}"
|
||||||
|
YANPM_AGENT_GID="${YANPM_AGENT_GID:-1000}"
|
||||||
|
# If a specific socket GID is requested, prefer that for the app group
|
||||||
|
YANPM_AGENT_GID_EFFECTIVE="${YANPM_AGENT_SOCK_GID:-${YANPM_AGENT_GID}}"
|
||||||
|
YANPM_AGENT_USER="${YANPM_AGENT_USER:-yanpm-agent}"
|
||||||
|
YANPM_AGENT_GROUP="${YANPM_AGENT_GROUP:-yanpm-agent}"
|
||||||
|
|
||||||
|
# Ensure group exists with desired GID
|
||||||
|
if grep -qE "^${YANPM_AGENT_GROUP}:" /etc/group 2>/dev/null; then
|
||||||
|
existing_gid=$(awk -F: -v g="${YANPM_AGENT_GROUP}" '$1==g{print $3}' /etc/group)
|
||||||
|
if [ "${existing_gid}" != "${YANPM_AGENT_GID_EFFECTIVE}" ]; then
|
||||||
|
delgroup "${YANPM_AGENT_GROUP}" || true
|
||||||
|
addgroup -g "${YANPM_AGENT_GID_EFFECTIVE}" "${YANPM_AGENT_GROUP}"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
addgroup -g "${YANPM_AGENT_GID_EFFECTIVE}" "${YANPM_AGENT_GROUP}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Ensure user exists with desired UID and primary group
|
||||||
|
if grep -qE "^${YANPM_AGENT_USER}:" /etc/passwd 2>/dev/null; then
|
||||||
|
existing_uid=$(awk -F: -v u="${YANPM_AGENT_USER}" '$1==u{print $3}' /etc/passwd)
|
||||||
|
if [ "${existing_uid}" != "${YANPM_AGENT_UID}" ]; then
|
||||||
|
deluser "${YANPM_AGENT_USER}" || true
|
||||||
|
adduser -D -u "${YANPM_AGENT_UID}" -G "${YANPM_AGENT_GROUP}" "${YANPM_AGENT_USER}"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
adduser -D -u "${YANPM_AGENT_UID}" -G "${YANPM_AGENT_GROUP}" "${YANPM_AGENT_USER}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Add app user to nginx group to allow reading configs
|
||||||
|
addgroup "${YANPM_AGENT_USER}" nginx || true
|
||||||
|
# Ensure runtime directories exist and fix ownership
|
||||||
|
|
||||||
|
mkdir -p /var/run/yanpm /app
|
||||||
|
if chown -R "${YANPM_AGENT_UID}:${YANPM_AGENT_GID_EFFECTIVE}" /var/run/yanpm 2>/dev/null; then
|
||||||
|
echo "chown: /var/run/yanpm -> ${YANPM_AGENT_UID}:${YANPM_AGENT_GID_EFFECTIVE}"
|
||||||
|
else
|
||||||
|
echo "Warning: failed to chown /var/run/yanpm to ${YANPM_AGENT_UID}:${YANPM_AGENT_GID_EFFECTIVE}. This is common for bind-mounted host volumes or rootless Docker." >&2
|
||||||
|
fi
|
||||||
|
|
||||||
|
if chown -R "${YANPM_AGENT_UID}:${YANPM_AGENT_GID_EFFECTIVE}" /app/yanpm-agent 2>/dev/null; then
|
||||||
|
echo "chown: /app/yanpm-agent -> ${YANPM_AGENT_UID}:${YANPM_AGENT_GID_EFFECTIVE}"
|
||||||
|
else
|
||||||
|
echo "Warning: failed to chown /app/yanpm-agent to ${YANPM_AGENT_UID}:${YANPM_AGENT_GID_EFFECTIVE}. Binary will still be used if permissions allow." >&2
|
||||||
|
fi
|
||||||
|
|
||||||
|
if chown "${YANPM_AGENT_UID}:${YANPM_AGENT_GID_EFFECTIVE}" /app 2>/dev/null; then
|
||||||
|
echo "chown: /app -> ${YANPM_AGENT_UID}:${YANPM_AGENT_GID_EFFECTIVE}"
|
||||||
|
else
|
||||||
|
echo "Warning: failed to chown /app to ${YANPM_AGENT_UID}:${YANPM_AGENT_GID_EFFECTIVE}." >&2
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "App user and group setup complete. UID:${YANPM_AGENT_UID} GID:${YANPM_AGENT_GID_EFFECTIVE}"
|
||||||
|
|
||||||
|
exit 0
|
||||||
170
apps/agent/docker/s6/cont-init.d/20-install-reload-wrapper
Normal file
170
apps/agent/docker/s6/cont-init.d/20-install-reload-wrapper
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
# This init script installs a minimal nginx reload wrapper and a sudoers
|
||||||
|
# entry so the `yanpm-agent` user can perform a controlled reload via sudo.
|
||||||
|
|
||||||
|
WRAPPER_PATH="/usr/local/sbin/yanpm-nginx-reload"
|
||||||
|
SUDOERS_PATH="/etc/sudoers.d/yanpm-agent"
|
||||||
|
AGENT_USER="${YANPM_AGENT_USER:-yanpm-agent}"
|
||||||
|
|
||||||
|
# validate wrapper
|
||||||
|
VALIDATE_PATH="/usr/local/sbin/yanpm-nginx-validate"
|
||||||
|
# validate file wrapper
|
||||||
|
VALIDATE_FILE_PATH="/usr/local/sbin/yanpm-nginx-validate-file"
|
||||||
|
|
||||||
|
echo "[cont-init.d] install-reload-wrapper: setting up nginx reload helper"
|
||||||
|
|
||||||
|
# find nginx binary
|
||||||
|
NGINX_BIN="$(command -v nginx || true)"
|
||||||
|
if [ -z "${NGINX_BIN}" ]; then
|
||||||
|
echo "Warning: nginx binary not found in PATH; wrapper will still be created but may fail at runtime." >&2
|
||||||
|
NGINX_BIN="/usr/sbin/nginx"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create wrapper
|
||||||
|
mkdir -p /usr/local/sbin /etc/sudoers.d
|
||||||
|
|
||||||
|
cat > "${WRAPPER_PATH}" <<- 'EOF'
|
||||||
|
#!/bin/sh
|
||||||
|
exec "@NGINX_BIN@" -c /etc/nginx/nginx.conf -s reload
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# Replace placeholder with actual path
|
||||||
|
sed -i "s|@NGINX_BIN@|${NGINX_BIN}|g" "${WRAPPER_PATH}" || true
|
||||||
|
|
||||||
|
chmod 0750 "${WRAPPER_PATH}"
|
||||||
|
chown root:root "${WRAPPER_PATH}" || true
|
||||||
|
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
|
||||||
|
# Create validate wrapper
|
||||||
|
cat > "${VALIDATE_PATH}" <<- 'EOF'
|
||||||
|
#!/bin/sh
|
||||||
|
exec "@NGINX_BIN@" -c /etc/nginx/nginx.conf -t
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# Replace placeholder with actual path in validate wrapper
|
||||||
|
sed -i "s|@NGINX_BIN@|${NGINX_BIN}|g" "${VALIDATE_PATH}" || true
|
||||||
|
|
||||||
|
chmod 0750 "${VALIDATE_PATH}"
|
||||||
|
chown root:root "${VALIDATE_PATH}" || true
|
||||||
|
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
|
||||||
|
# Create validate file wrapper (secure)
|
||||||
|
cat > "${VALIDATE_FILE_PATH}" <<-'EOF'
|
||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
if [ $# -ne 1 ]; then
|
||||||
|
echo "Usage: $0 <nginx-config-file>" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
INPUT="$1"
|
||||||
|
|
||||||
|
# Resolve absolute path
|
||||||
|
if command -v readlink >/dev/null 2>&1; then
|
||||||
|
TARGET="$(readlink -f -- "$INPUT" 2>/dev/null || true)"
|
||||||
|
elif command -v realpath >/dev/null 2>&1; then
|
||||||
|
TARGET="$(realpath -- "$INPUT" 2>/dev/null || true)"
|
||||||
|
else
|
||||||
|
echo "Error: no path resolver (readlink/realpath) available" >&2
|
||||||
|
exit 3
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z "$TARGET" ]; then
|
||||||
|
echo "Error: cannot resolve path: $INPUT" >&2
|
||||||
|
exit 4
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Must be a regular file and not a symlink
|
||||||
|
if [ ! -f "$TARGET" ] || [ -L "$TARGET" ]; then
|
||||||
|
echo "Error: ${TARGET} is not a regular file" >&2
|
||||||
|
exit 5
|
||||||
|
fi
|
||||||
|
|
||||||
|
# must be created by agent user
|
||||||
|
AGENT_UID="$(id -u yanpm-agent 2>/dev/null || true)"
|
||||||
|
if [ -z "$AGENT_UID" ]; then
|
||||||
|
echo "Error: yanpm-agent user not found" >&2
|
||||||
|
exit 6
|
||||||
|
fi
|
||||||
|
|
||||||
|
FILE_UID="$(stat -c %u -- "$TARGET" 2>/dev/null || true)"
|
||||||
|
if [ "$FILE_UID" != "$AGENT_UID" ]; then
|
||||||
|
echo "Error: ${TARGET} not owned by yanpm-agent user" >&2
|
||||||
|
exit 7
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Ensure file is not world-writable; allow typical 664 (rw-rw-r--)
|
||||||
|
if command -v stat >/dev/null 2>&1; then
|
||||||
|
MODE="$(stat -c %a -- "$TARGET" 2>/dev/null || true)"
|
||||||
|
if [ -n "$MODE" ]; then
|
||||||
|
OTHERS=$(( MODE % 10 ))
|
||||||
|
if [ $(( OTHERS & 2 )) -ne 0 ]; then
|
||||||
|
echo "Error: ${TARGET} is world-writable" >&2
|
||||||
|
exit 8
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
elif command -v find >/dev/null 2>&1; then
|
||||||
|
if find "$TARGET" -maxdepth 0 -perm /002 -print -quit >/dev/null 2>&1; then
|
||||||
|
echo "Error: ${TARGET} is world-writable" >&2
|
||||||
|
exit 8
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
exec "@NGINX_BIN@" -c "$TARGET" -t
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# Replace placeholder with actual path in validate file wrapper
|
||||||
|
sed -i "s|@NGINX_BIN@|${NGINX_BIN}|g" "${VALIDATE_FILE_PATH}" || true
|
||||||
|
chmod 0750 "${VALIDATE_FILE_PATH}"
|
||||||
|
chown root:root "${VALIDATE_FILE_PATH}" || true
|
||||||
|
|
||||||
|
echo "Created wrapper: ${WRAPPER_PATH} (owned by root, mode 750)"
|
||||||
|
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
|
||||||
|
# Ensure sudoers entry exists allowing the agent to run only this wrapper as root
|
||||||
|
if command -v sudo >/dev/null 2>&1; then
|
||||||
|
echo "sudo present; creating sudoers entry"
|
||||||
|
cat > "${SUDOERS_PATH}" <<- EOF
|
||||||
|
# Allow ${AGENT_USER} to run the nginx reload and validate wrappers without a password
|
||||||
|
${AGENT_USER} ALL=(root) NOPASSWD: ${WRAPPER_PATH}, ${VALIDATE_PATH}, ${VALIDATE_FILE_PATH}
|
||||||
|
EOF
|
||||||
|
chmod 0440 "${SUDOERS_PATH}" || true
|
||||||
|
echo "Wrote sudoers entry: ${SUDOERS_PATH}"
|
||||||
|
else
|
||||||
|
echo "sudo not found; attempting to install"
|
||||||
|
if command -v apk >/dev/null 2>&1; then
|
||||||
|
apk add --no-cache sudo || true
|
||||||
|
elif command -v apt-get >/dev/null 2>&1; then
|
||||||
|
apt-get update || true
|
||||||
|
apt-get install -y sudo || true
|
||||||
|
elif command -v yum >/dev/null 2>&1; then
|
||||||
|
yum install -y sudo || true
|
||||||
|
else
|
||||||
|
echo "No known package manager to install sudo; please ensure sudo is available in the image." >&2
|
||||||
|
fi
|
||||||
|
|
||||||
|
if command -v sudo >/dev/null 2>&1; then
|
||||||
|
cat > "${SUDOERS_PATH}" <<- EOF
|
||||||
|
# Allow ${AGENT_USER} to run the nginx reload and validate wrappers without a password
|
||||||
|
${AGENT_USER} ALL=(root) NOPASSWD: ${WRAPPER_PATH}, ${VALIDATE_PATH}, ${VALIDATE_FILE_PATH}
|
||||||
|
EOF
|
||||||
|
chmod 0440 "${SUDOERS_PATH}" || true
|
||||||
|
echo "Installed sudo and wrote sudoers entry: ${SUDOERS_PATH}"
|
||||||
|
else
|
||||||
|
echo "Failed to install sudo; the agent will not be able to reload nginx via sudo." >&2
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit 0
|
||||||
5
apps/agent/docker/s6/services.d/agent/run
Normal file
5
apps/agent/docker/s6/services.d/agent/run
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Run the agent as the unprivileged 'yanpm-agent' user
|
||||||
|
cd /app
|
||||||
|
echo "Starting yanpm-agent..."
|
||||||
|
exec s6-setuidgid yanpm-agent ./yanpm-agent
|
||||||
3
apps/agent/docker/s6/services.d/nginx/run
Normal file
3
apps/agent/docker/s6/services.d/nginx/run
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Run nginx in foreground (s6 will supervise it)
|
||||||
|
exec nginx -g 'daemon off;'
|
||||||
2
apps/agent/justfile
Normal file
2
apps/agent/justfile
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
build-docker:
|
||||||
|
docker build -t yanpm/agent:latest .
|
||||||
292
apps/agent/src/commands.rs
Normal file
292
apps/agent/src/commands.rs
Normal file
@@ -0,0 +1,292 @@
|
|||||||
|
mod reload;
|
||||||
|
mod run;
|
||||||
|
mod validate;
|
||||||
|
mod write_config;
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicU64, Ordering},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
use tokio::sync::{Mutex, RwLock};
|
||||||
|
use tokio_cron_scheduler::{Job, JobScheduler};
|
||||||
|
use tracing::{error, info};
|
||||||
|
|
||||||
|
use crate::commands::write_config::INTERNAL_CONFIG_FOLDER_NAME;
|
||||||
|
|
||||||
|
const OLD_CONFIG_CLEANUP_THRESHOLD: u64 = 3600;
|
||||||
|
|
||||||
|
pub struct NginxService {
|
||||||
|
// lock for nginx reload, and timestamp tracking
|
||||||
|
nginx_lock: Mutex<()>,
|
||||||
|
last_applied: AtomicU64,
|
||||||
|
// lock for write_config per (config_name, timestamp)
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
|
write_config_lock: RwLock<HashMap<(String, u64), Arc<RwLock<()>>>>,
|
||||||
|
// commands
|
||||||
|
reload_cmd: Arc<reload::ReloadCommand>,
|
||||||
|
validate_cmd: Arc<validate::ValidateCommand>,
|
||||||
|
write_config_cmd: Arc<write_config::WriteConfigCommand>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NginxService {
|
||||||
|
pub async fn new(
|
||||||
|
scheduler: Arc<JobScheduler>,
|
||||||
|
nginx_config_dir: std::path::PathBuf,
|
||||||
|
) -> Result<Arc<Self>, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let nginx_service = Arc::new(NginxService {
|
||||||
|
nginx_lock: Mutex::new(()),
|
||||||
|
last_applied: AtomicU64::new(0),
|
||||||
|
write_config_lock: RwLock::new(HashMap::new()),
|
||||||
|
// commands
|
||||||
|
reload_cmd: Arc::new(reload::ReloadCommand::default()),
|
||||||
|
validate_cmd: Arc::new(validate::ValidateCommand::new(nginx_config_dir.clone())),
|
||||||
|
write_config_cmd: Arc::new(write_config::WriteConfigCommand::new(nginx_config_dir)),
|
||||||
|
});
|
||||||
|
let mut nginx_service_clone = nginx_service.clone();
|
||||||
|
|
||||||
|
scheduler
|
||||||
|
.clone()
|
||||||
|
// cleanup every 10 minutes
|
||||||
|
.add(Job::new_async("0 */10 * * * *", move |_uuid, _l| {
|
||||||
|
info!("Running nginx_service cleanup job");
|
||||||
|
let nginx_service_clone = nginx_service_clone.clone();
|
||||||
|
let job = Box::pin(async move {
|
||||||
|
nginx_service_clone.cleanup_unused_lock().await;
|
||||||
|
});
|
||||||
|
info!("NginxService cleanup job completed");
|
||||||
|
job
|
||||||
|
})?)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
nginx_service_clone = nginx_service.clone();
|
||||||
|
|
||||||
|
scheduler
|
||||||
|
.clone()
|
||||||
|
// cleanup every hour
|
||||||
|
.add(Job::new_async("0 0 */1 * * *", move |_uuid, _l| {
|
||||||
|
info!("Running nginx_service old config cleanup job");
|
||||||
|
let nginx_service_clone = nginx_service_clone.clone();
|
||||||
|
let job = Box::pin(async move {
|
||||||
|
nginx_service_clone.cleanup_old_configs().await;
|
||||||
|
});
|
||||||
|
info!("NginxService old config cleanup job completed");
|
||||||
|
job
|
||||||
|
})?)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(nginx_service)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn validate_and_reload(
|
||||||
|
&self,
|
||||||
|
config_name: &str,
|
||||||
|
timestamp: u64,
|
||||||
|
) -> Result<(i32, String), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let cur = self.last_applied.load(Ordering::SeqCst);
|
||||||
|
if cur > timestamp {
|
||||||
|
return Err("Another operation is in progress with higher timestamp value".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// acquire write lock to update nginx_lock
|
||||||
|
let _nginx_guard = self.nginx_lock.lock().await;
|
||||||
|
// acquire write lock for this config+timestamp
|
||||||
|
let rw_lock = self.acquire_file_write_lock(config_name, timestamp).await;
|
||||||
|
let _guard = rw_lock.write().await;
|
||||||
|
|
||||||
|
match self
|
||||||
|
.reload_cmd
|
||||||
|
.validate_and_reload(config_name, timestamp, self.validate_cmd.clone())
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok((code, output)) => {
|
||||||
|
// update last_applied
|
||||||
|
self.last_applied.store(timestamp, Ordering::SeqCst);
|
||||||
|
Ok((code, output))
|
||||||
|
}
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn write_config(
|
||||||
|
&self,
|
||||||
|
config_name: &str,
|
||||||
|
timestamp: u64,
|
||||||
|
content: &str,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let rw_lock = self.acquire_file_write_lock(config_name, timestamp).await;
|
||||||
|
let _guard = rw_lock.write().await;
|
||||||
|
// call the write_config command
|
||||||
|
self.write_config_cmd
|
||||||
|
.write_config(config_name, timestamp, content)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn validate(
|
||||||
|
&self,
|
||||||
|
config_name: &str,
|
||||||
|
timestamp: u64,
|
||||||
|
) -> Result<(i32, String), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
self.validate_cmd.validate(config_name, timestamp).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn cleanup_unused_lock(&self) {
|
||||||
|
let mut _write_lock = self.write_config_lock.write().await;
|
||||||
|
(*_write_lock).retain(|_, lock| {
|
||||||
|
// retain only locks that are currently held (readers or writers)
|
||||||
|
lock.try_write().is_err()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn cleanup_old_configs(&self) {
|
||||||
|
// list all files within nginx_config_dir/YANPM that is older than now - OLD_CONFIG_CLEANUP_THRESHOLD
|
||||||
|
let cutoff = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_secs()
|
||||||
|
- OLD_CONFIG_CLEANUP_THRESHOLD;
|
||||||
|
|
||||||
|
let nginx_config_dir = self.validate_cmd.nginx_config_dir();
|
||||||
|
let yanpm_dir = nginx_config_dir.join(INTERNAL_CONFIG_FOLDER_NAME);
|
||||||
|
|
||||||
|
let read_dir = match tokio::fs::read_dir(&yanpm_dir).await {
|
||||||
|
Ok(rd) => rd,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
// directory does not exist, nothing to clean up
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
error!(
|
||||||
|
"Error reading {} config directory {}: {}",
|
||||||
|
INTERNAL_CONFIG_FOLDER_NAME,
|
||||||
|
yanpm_dir.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
tokio::pin!(read_dir);
|
||||||
|
while let Some(entry) = read_dir.next_entry().await.unwrap_or(None) {
|
||||||
|
let metadata = match entry.metadata().await {
|
||||||
|
Ok(md) => md,
|
||||||
|
Err(e) => {
|
||||||
|
error!(
|
||||||
|
"Error getting metadata for file {}: {}",
|
||||||
|
entry.path().display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Ok(modified) = metadata.modified()
|
||||||
|
&& let Ok(duration) = modified.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
{
|
||||||
|
let mtime_secs = duration.as_secs();
|
||||||
|
if mtime_secs < cutoff {
|
||||||
|
// file is older than cutoff, remove it
|
||||||
|
if let Err(e) = tokio::fs::remove_file(entry.path()).await {
|
||||||
|
error!(
|
||||||
|
"Error removing old config file {}: {}",
|
||||||
|
entry.path().display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
info!("Removed old config file {}", entry.path().display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn acquire_file_write_lock(&self, config_name: &str, timestamp: u64) -> Arc<RwLock<()>> {
|
||||||
|
let mut write_lock = self.write_config_lock.write().await;
|
||||||
|
write_lock
|
||||||
|
.entry((config_name.to_string(), timestamp))
|
||||||
|
.or_insert_with(|| Arc::new(RwLock::new(())))
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::error::Error;
|
||||||
|
use std::sync::Arc as StdArc;
|
||||||
|
use tokio::time::{Duration, sleep};
|
||||||
|
|
||||||
|
impl NginxService {
|
||||||
|
// Test helper that simulates a long-running reload without invoking external commands.
|
||||||
|
pub async fn test_simulated_reload(
|
||||||
|
&self,
|
||||||
|
config_name: &str,
|
||||||
|
timestamp: u64,
|
||||||
|
delay_ms: u64,
|
||||||
|
) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||||
|
// pre-check
|
||||||
|
let cur = self.last_applied.load(Ordering::SeqCst);
|
||||||
|
if cur >= timestamp {
|
||||||
|
return Err("stale".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// acquire exclusive lock and re-check
|
||||||
|
let _nginx_guard = self.nginx_lock.lock().await;
|
||||||
|
let cur2 = self.last_applied.load(Ordering::SeqCst);
|
||||||
|
if cur2 >= timestamp {
|
||||||
|
return Err("stale".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// per-file lock
|
||||||
|
let rw_lock = self.acquire_file_write_lock(config_name, timestamp).await;
|
||||||
|
let _guard = rw_lock.write().await;
|
||||||
|
|
||||||
|
// simulate operation
|
||||||
|
sleep(Duration::from_millis(delay_ms)).await;
|
||||||
|
|
||||||
|
// on success update last_applied
|
||||||
|
let mut prev = self.last_applied.load(Ordering::SeqCst);
|
||||||
|
while prev < timestamp {
|
||||||
|
match self.last_applied.compare_exchange(
|
||||||
|
prev,
|
||||||
|
timestamp,
|
||||||
|
Ordering::SeqCst,
|
||||||
|
Ordering::SeqCst,
|
||||||
|
) {
|
||||||
|
Ok(_) => break,
|
||||||
|
Err(next) => prev = next,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn concurrent_stale_is_rejected() {
|
||||||
|
let scheduler = StdArc::new(JobScheduler::new().await.unwrap());
|
||||||
|
let svc = NginxService::new(scheduler.clone(), std::env::temp_dir())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let s1 = svc.clone();
|
||||||
|
let h1 = tokio::spawn(async move { s1.test_simulated_reload("cfg", 2, 200).await });
|
||||||
|
|
||||||
|
// let second start shortly after first so it will wait for the mutex
|
||||||
|
sleep(Duration::from_millis(20)).await;
|
||||||
|
|
||||||
|
let s2 = svc.clone();
|
||||||
|
let h2 = tokio::spawn(async move { s2.test_simulated_reload("cfg", 1, 10).await });
|
||||||
|
|
||||||
|
let r1 = h1.await.unwrap();
|
||||||
|
assert!(r1.is_ok(), "first (newer) task should succeed");
|
||||||
|
|
||||||
|
let r2 = h2.await.unwrap();
|
||||||
|
assert!(
|
||||||
|
r2.is_err(),
|
||||||
|
"second (older) task should be rejected as stale"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
109
apps/agent/src/commands/reload.rs
Normal file
109
apps/agent/src/commands/reload.rs
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
use std::path::Path;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
use tracing::error;
|
||||||
|
|
||||||
|
use crate::commands::write_config::INTERNAL_CONFIG_FOLDER_NAME;
|
||||||
|
use crate::commands::{run::run_cmd, validate::ValidateCommand};
|
||||||
|
|
||||||
|
pub struct ReloadCommand {
|
||||||
|
is_reloading: Mutex<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ReloadResetGuard<'a> {
|
||||||
|
guard: tokio::sync::MutexGuard<'a, bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Drop for ReloadResetGuard<'a> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
*self.guard = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ReloadCommand {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
is_reloading: Mutex::new(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReloadCommand {
|
||||||
|
pub async fn validate_and_reload(
|
||||||
|
&self,
|
||||||
|
config_name: &str,
|
||||||
|
timestamp: u64,
|
||||||
|
validate_cmd: Arc<ValidateCommand>,
|
||||||
|
) -> Result<(i32, String), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
// ensure the written fragment exists
|
||||||
|
validate_cmd.validate(config_name, timestamp).await?;
|
||||||
|
|
||||||
|
// Now atomically swap the YANPM.conf symlink to point to the new fragment
|
||||||
|
// so nginx -t validates the composed main config. If validation fails,
|
||||||
|
// attempt to restore the previous symlink.
|
||||||
|
let filename = crate::commands::run::to_file_name(config_name, timestamp)?;
|
||||||
|
let nginx_dir = validate_cmd.nginx_config_dir();
|
||||||
|
let symlink_path = nginx_dir.join("YANPM.conf");
|
||||||
|
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
|
||||||
|
let tmp_name = format!("YANPM.conf.tmp.{}.{}", std::process::id(), now);
|
||||||
|
let tmp_path = nginx_dir.join(&tmp_name);
|
||||||
|
|
||||||
|
// prepare relative target: INTERNAL_CONFIG_FOLDER_NAME/<filename>
|
||||||
|
let rel_target = Path::new(INTERNAL_CONFIG_FOLDER_NAME).join(&filename);
|
||||||
|
|
||||||
|
// read previous target if exists
|
||||||
|
let previous_target = std::fs::read_link(&symlink_path).ok();
|
||||||
|
|
||||||
|
// Acquire reload guard before mutating the symlink to avoid races
|
||||||
|
let reloading_lock = self.is_reloading.lock().await;
|
||||||
|
if *reloading_lock {
|
||||||
|
return Err("Reload already in progress".into());
|
||||||
|
}
|
||||||
|
// set flag to true and ensure it is reset on drop
|
||||||
|
let mut mut_guard = reloading_lock;
|
||||||
|
*mut_guard = true;
|
||||||
|
let _reset_guard = ReloadResetGuard { guard: mut_guard };
|
||||||
|
|
||||||
|
// create temporary symlink and atomically rename into place
|
||||||
|
std::os::unix::fs::symlink(&rel_target, &tmp_path)?;
|
||||||
|
tokio::fs::rename(&tmp_path, &symlink_path).await?;
|
||||||
|
|
||||||
|
// validate composed main config now that symlink points to new fragment
|
||||||
|
if let Err(e) = validate_cmd.validate_all().await {
|
||||||
|
// restore previous symlink state while still holding the guard
|
||||||
|
if let Some(prev) = previous_target {
|
||||||
|
let restore_tmp =
|
||||||
|
nginx_dir.join(format!("YANPM.conf.restore.{}.{}", std::process::id(), now));
|
||||||
|
std::os::unix::fs::symlink(&prev, &restore_tmp)?;
|
||||||
|
if let Err(err) = tokio::fs::rename(&restore_tmp, &symlink_path).await {
|
||||||
|
error!(
|
||||||
|
"Failed to restore previous YANPM.conf symlink after validation error: {}",
|
||||||
|
err
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if let Err(err) = tokio::fs::remove_file(&symlink_path).await {
|
||||||
|
error!(
|
||||||
|
"Failed to remove YANPM.conf symlink after validation error: {}",
|
||||||
|
err
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// reload the running nginx master process (no -c) so it reloads its configured main config
|
||||||
|
// Prefer the restricted sudo wrapper if available, fall back to direct nginx reload.
|
||||||
|
// TODO: allow configuring the path to the wrapper
|
||||||
|
match run_cmd("sudo", &["-n", "/usr/local/sbin/yanpm-nginx-reload"], 10).await {
|
||||||
|
Ok(res) => Ok(res),
|
||||||
|
Err(e) => {
|
||||||
|
error!(
|
||||||
|
"sudo reload wrapper failed, falling back to direct nginx reload: {}",
|
||||||
|
e
|
||||||
|
);
|
||||||
|
run_cmd("nginx", &["-s", "reload"], 10).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
85
apps/agent/src/commands/run.rs
Normal file
85
apps/agent/src/commands/run.rs
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use tokio::{process::Command, time::timeout};
|
||||||
|
use tracing::error;
|
||||||
|
|
||||||
|
pub fn to_file_name(
|
||||||
|
config_name: &str,
|
||||||
|
timestamp: u64,
|
||||||
|
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
// reject empty or unsafe names to avoid path traversal or invalid filesystem chars
|
||||||
|
if config_name.is_empty() {
|
||||||
|
return Err("config_name is empty".into());
|
||||||
|
}
|
||||||
|
if config_name.len() > 255 {
|
||||||
|
return Err("config_name too long".into());
|
||||||
|
}
|
||||||
|
if config_name.contains('/') || config_name.contains('\\') || config_name.contains("..") {
|
||||||
|
return Err("config_name contains invalid path characters".into());
|
||||||
|
}
|
||||||
|
if !config_name
|
||||||
|
.chars()
|
||||||
|
.all(|c| c.is_ascii_alphanumeric() || "-._".contains(c))
|
||||||
|
{
|
||||||
|
return Err("config_name contains invalid characters".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(format!("{}_{}.conf", timestamp, config_name))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run_cmd(
|
||||||
|
cmd: &str,
|
||||||
|
args: &[&str],
|
||||||
|
dur_s: u64,
|
||||||
|
) -> Result<(i32, String), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let mut c = Command::new(cmd);
|
||||||
|
c.args(args);
|
||||||
|
let res = timeout(Duration::from_secs(dur_s), c.output()).await;
|
||||||
|
let out = match res {
|
||||||
|
Ok(Ok(out)) => out,
|
||||||
|
Ok(Err(e)) => return Err(Box::new(e)),
|
||||||
|
Err(_) => {
|
||||||
|
return Err(Box::new(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::TimedOut,
|
||||||
|
"command timeout",
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let code = out.status.code().unwrap_or(-1);
|
||||||
|
let output = String::from_utf8_lossy(&[out.stdout, out.stderr].concat()).to_string();
|
||||||
|
if code != 0 {
|
||||||
|
error!("command failed ({}): {}", code, output);
|
||||||
|
return Err(format!("command failed ({}): {}", code, output).into());
|
||||||
|
}
|
||||||
|
Ok((code, output))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::to_file_name;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn to_file_name_valid() {
|
||||||
|
let res = to_file_name("myconf", 1234).expect("should succeed");
|
||||||
|
assert_eq!(res, "1234_myconf.conf");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn to_file_name_empty() {
|
||||||
|
assert!(to_file_name("", 1).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn to_file_name_invalid_chars() {
|
||||||
|
assert!(to_file_name("bad/name", 1).is_err());
|
||||||
|
assert!(to_file_name("bad\\name", 1).is_err());
|
||||||
|
assert!(to_file_name("bad..name", 1).is_err());
|
||||||
|
assert!(to_file_name("bad$name", 1).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn to_file_name_too_long() {
|
||||||
|
let long = "a".repeat(300);
|
||||||
|
assert!(to_file_name(&long, 1).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
166
apps/agent/src/commands/validate.rs
Normal file
166
apps/agent/src/commands/validate.rs
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
use tracing::{info, warn};
|
||||||
|
|
||||||
|
use crate::commands::{run::run_cmd, write_config::INTERNAL_CONFIG_FOLDER_NAME};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
pub struct ValidateCommand {
|
||||||
|
nginx_config_dir: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ValidateCommand {
|
||||||
|
pub fn new(nginx_config_dir: PathBuf) -> Self {
|
||||||
|
Self { nginx_config_dir }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn nginx_config_dir(&self) -> PathBuf {
|
||||||
|
self.nginx_config_dir.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn validate_all(
|
||||||
|
&self,
|
||||||
|
) -> Result<(i32, String), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
// Try a normal config test first. If it fails due to pid permission
|
||||||
|
// errors (common when running unprivileged against /run/nginx.pid),
|
||||||
|
// retry with a writable pid override so validation can succeed.
|
||||||
|
match run_cmd("nginx", &["-t"], 10).await {
|
||||||
|
Ok(res) => Ok(res),
|
||||||
|
Err(e) => {
|
||||||
|
info!(
|
||||||
|
"nginx -t failed: {}. Trying with privileged wrapper or writable pid override.",
|
||||||
|
e
|
||||||
|
);
|
||||||
|
let es = e.to_string();
|
||||||
|
if es.contains("/run/nginx.pid") && es.contains("Permission denied") {
|
||||||
|
// Try privileged validate wrapper if available (allows the agent to run
|
||||||
|
// nginx -t via sudo without modifying the main config).
|
||||||
|
match run_cmd(
|
||||||
|
"sudo",
|
||||||
|
// TODO: allow configuring the path to the wrapper
|
||||||
|
&["-n", "/usr/local/sbin/yanpm-nginx-validate"],
|
||||||
|
10,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(res) => return Ok(res),
|
||||||
|
Err(e) => {
|
||||||
|
warn!(
|
||||||
|
"Privileged validate wrapper failed: {}. Falling back to writable pid override.",
|
||||||
|
e
|
||||||
|
);
|
||||||
|
// Fallback to the existing writable-pid override if sudo wrapper
|
||||||
|
// isn't available or fails.
|
||||||
|
let pid_path = format!(
|
||||||
|
"{}/yanpm-validate-{}.pid",
|
||||||
|
std::env::temp_dir().display(),
|
||||||
|
std::process::id()
|
||||||
|
);
|
||||||
|
let g_arg = format!("pid {};", pid_path);
|
||||||
|
let args_vec = ["-t".to_string(), "-g".to_string(), g_arg];
|
||||||
|
let args_ref: Vec<&str> = args_vec.iter().map(|s| s.as_str()).collect();
|
||||||
|
return run_cmd("nginx", args_ref.as_slice(), 10).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn validate(
|
||||||
|
&self,
|
||||||
|
config_name: &str,
|
||||||
|
timestamp: u64,
|
||||||
|
) -> Result<(i32, String), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let filename = crate::commands::run::to_file_name(config_name, timestamp)?;
|
||||||
|
// fragments are written into the YANPM subdirectory
|
||||||
|
let full_path = self
|
||||||
|
.nginx_config_dir
|
||||||
|
.join(INTERNAL_CONFIG_FOLDER_NAME)
|
||||||
|
.join(&filename);
|
||||||
|
|
||||||
|
// ensure the fragment file exists
|
||||||
|
if tokio::fs::metadata(&full_path).await.is_err() {
|
||||||
|
return Err(format!("Config file not found: {}", full_path.display()).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a temporary wrapper nginx config that provides the required
|
||||||
|
// top-level sections (`events` and `http`) and includes the fragment.
|
||||||
|
let fragment_path = full_path.to_str().ok_or("invalid config path")?.to_string();
|
||||||
|
|
||||||
|
let mut tmp_path = std::env::temp_dir();
|
||||||
|
let tmp_name = format!("yanpm-validate-{}-{}.conf", timestamp, std::process::id());
|
||||||
|
tmp_path.push(tmp_name);
|
||||||
|
|
||||||
|
let wrapper = format!(
|
||||||
|
"worker_processes 1;\nevents {{ worker_connections 1024; }}\nhttp {{\n include {};\n}}\n",
|
||||||
|
fragment_path
|
||||||
|
);
|
||||||
|
|
||||||
|
// Write the temporary wrapper file
|
||||||
|
tokio::fs::write(&tmp_path, wrapper).await?;
|
||||||
|
let tmp_path_str = tmp_path
|
||||||
|
.to_str()
|
||||||
|
.ok_or("invalid temp config path")?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
// Run the test against the wrapper, telling nginx to place its pid
|
||||||
|
// somewhere writable so the config test doesn't fail with permission
|
||||||
|
// errors when running as an unprivileged user.
|
||||||
|
let result = match run_cmd("nginx", &["-t", "-c", &tmp_path_str], 10).await {
|
||||||
|
Ok(res) => Ok(res),
|
||||||
|
Err(e) => {
|
||||||
|
info!(
|
||||||
|
"nginx -t failed: {}. Trying with privileged wrapper or writable pid override.",
|
||||||
|
e
|
||||||
|
);
|
||||||
|
let es = e.to_string();
|
||||||
|
if es.contains("/run/nginx.pid") && es.contains("Permission denied") {
|
||||||
|
// Try privileged validate wrapper if available (allows the agent to run
|
||||||
|
// nginx -t via sudo without modifying the main config).
|
||||||
|
match run_cmd(
|
||||||
|
"sudo",
|
||||||
|
// TODO: allow configuring the path to the wrapper
|
||||||
|
&[
|
||||||
|
"-n",
|
||||||
|
"/usr/local/sbin/yanpm-nginx-validate-file",
|
||||||
|
&tmp_path_str,
|
||||||
|
],
|
||||||
|
10,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(res) => return Ok(res),
|
||||||
|
Err(e) => {
|
||||||
|
warn!(
|
||||||
|
"Privileged validate wrapper failed: {}. Falling back to writable pid override.",
|
||||||
|
e
|
||||||
|
);
|
||||||
|
let pid_path = format!(
|
||||||
|
"{}/yanpm-validate-{}.pid",
|
||||||
|
std::env::temp_dir().display(),
|
||||||
|
std::process::id()
|
||||||
|
);
|
||||||
|
let g_arg = format!("pid {};", pid_path);
|
||||||
|
|
||||||
|
let args_vec = [
|
||||||
|
"-t".to_string(),
|
||||||
|
"-c".to_string(),
|
||||||
|
tmp_path_str.clone(),
|
||||||
|
"-g".to_string(),
|
||||||
|
g_arg,
|
||||||
|
];
|
||||||
|
let args_ref: Vec<&str> = args_vec.iter().map(|s| s.as_str()).collect();
|
||||||
|
|
||||||
|
return run_cmd("nginx", args_ref.as_slice(), 10).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let _ = tokio::fs::remove_file(&tmp_path).await;
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
133
apps/agent/src/commands/write_config.rs
Normal file
133
apps/agent/src/commands/write_config.rs
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
use tokio::io::AsyncWriteExt;
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
|
use crate::commands::run::to_file_name;
|
||||||
|
|
||||||
|
pub const INTERNAL_CONFIG_FOLDER_NAME: &str = "YANPM";
|
||||||
|
const FILE_SIZE_LIMIT: usize = 10 * 1024 * 1024; // 10MB
|
||||||
|
|
||||||
|
pub struct WriteConfigCommand {
|
||||||
|
nginx_config_dir: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WriteConfigCommand {
|
||||||
|
pub fn new(nginx_config_dir: PathBuf) -> Self {
|
||||||
|
Self { nginx_config_dir }
|
||||||
|
}
|
||||||
|
pub async fn write_config(
|
||||||
|
&self,
|
||||||
|
config_name: &str,
|
||||||
|
timestamp: u64,
|
||||||
|
content: &str,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let filename = to_file_name(config_name, timestamp)?;
|
||||||
|
let path = self.nginx_config_dir.clone();
|
||||||
|
// ensure main config dir exists
|
||||||
|
tokio::fs::create_dir_all(&path).await?;
|
||||||
|
info!("Writing config to {:?}", path.join(&filename));
|
||||||
|
|
||||||
|
// create YANPM subdir where fragment files live
|
||||||
|
let yanpm_dir = path.join(INTERNAL_CONFIG_FOLDER_NAME);
|
||||||
|
tokio::fs::create_dir_all(&yanpm_dir).await?;
|
||||||
|
let final_path = yanpm_dir.join(&filename);
|
||||||
|
|
||||||
|
// limit size to 10MB
|
||||||
|
if content.len() > FILE_SIZE_LIMIT {
|
||||||
|
return Err(format!(
|
||||||
|
"content exceeds {}MB size limit",
|
||||||
|
FILE_SIZE_LIMIT / (1024 * 1024)
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// create a temporary filename in the same directory for atomic replace
|
||||||
|
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
|
||||||
|
let tmp_filename = format!("{}.tmp.{}.{}", filename, std::process::id(), now);
|
||||||
|
// create tmp file in the same directory as final file to ensure atomic rename
|
||||||
|
let tmp_path = yanpm_dir.join(tmp_filename);
|
||||||
|
|
||||||
|
let mut file = tokio::fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.write(true)
|
||||||
|
.truncate(true)
|
||||||
|
.open(&tmp_path)
|
||||||
|
.await?;
|
||||||
|
file.write_all(content.as_bytes()).await?;
|
||||||
|
// ensure data is flushed to disk; propagate errors
|
||||||
|
file.sync_all().await?;
|
||||||
|
|
||||||
|
// atomically move the tmp file into the YANPM dir
|
||||||
|
tokio::fs::rename(&tmp_path, &final_path).await?;
|
||||||
|
|
||||||
|
// set explicit permissions (rw-r-----)
|
||||||
|
tokio::fs::set_permissions(&final_path, std::fs::Permissions::from_mode(0o640)).await?;
|
||||||
|
info!("Config written and permissions set for {:?}", final_path);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{INTERNAL_CONFIG_FOLDER_NAME, WriteConfigCommand};
|
||||||
|
use std::time::SystemTime;
|
||||||
|
use std::time::UNIX_EPOCH;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn write_config_success_and_cleanup() {
|
||||||
|
let base = std::env::temp_dir().join(format!(
|
||||||
|
"yanpm_test_{}_{}",
|
||||||
|
std::process::id(),
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_nanos()
|
||||||
|
));
|
||||||
|
// ensure clean
|
||||||
|
let _ = tokio::fs::remove_dir_all(&base).await;
|
||||||
|
let cmd = WriteConfigCommand::new(base.clone());
|
||||||
|
|
||||||
|
let config_name = "unittest";
|
||||||
|
let timestamp = 42u64;
|
||||||
|
let content = "hello world";
|
||||||
|
|
||||||
|
cmd.write_config(config_name, timestamp, content)
|
||||||
|
.await
|
||||||
|
.expect("write should succeed");
|
||||||
|
|
||||||
|
let filename = super::to_file_name(config_name, timestamp).unwrap();
|
||||||
|
let final_path = base.join(INTERNAL_CONFIG_FOLDER_NAME).join(&filename);
|
||||||
|
let data = tokio::fs::read_to_string(&final_path)
|
||||||
|
.await
|
||||||
|
.expect("file should exist");
|
||||||
|
assert_eq!(data, content);
|
||||||
|
|
||||||
|
// cleanup
|
||||||
|
tokio::fs::remove_dir_all(&base).await.expect("cleanup");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn write_config_size_limit() {
|
||||||
|
let base = std::env::temp_dir().join(format!(
|
||||||
|
"yanpm_test_{}_{}",
|
||||||
|
std::process::id(),
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_nanos()
|
||||||
|
));
|
||||||
|
let _ = tokio::fs::remove_dir_all(&base).await;
|
||||||
|
let cmd = WriteConfigCommand::new(base.clone());
|
||||||
|
|
||||||
|
// exceed 10MB limit
|
||||||
|
let large = vec![b'a'; 10 * 1024 * 1024 + 1];
|
||||||
|
let large_str = String::from_utf8_lossy(&large).to_string();
|
||||||
|
|
||||||
|
let res = cmd.write_config("big", 1, &large_str).await;
|
||||||
|
assert!(res.is_err());
|
||||||
|
|
||||||
|
let _ = tokio::fs::remove_dir_all(&base).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
221
apps/agent/src/main.rs
Normal file
221
apps/agent/src/main.rs
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
#![forbid(unsafe_code)]
|
||||||
|
|
||||||
|
mod commands;
|
||||||
|
mod openapi;
|
||||||
|
mod routes;
|
||||||
|
|
||||||
|
use axum::routing::get;
|
||||||
|
use axum::{Router, routing::post};
|
||||||
|
use clap::Parser;
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tokio::net::UnixListener;
|
||||||
|
use tracing::{error, info, warn};
|
||||||
|
|
||||||
|
use crate::commands::NginxService;
|
||||||
|
use crate::openapi::{GenerateOpenapiArgs, generate_openapi_doc};
|
||||||
|
use crate::routes::{status, validate, validate_and_reload, write_config};
|
||||||
|
|
||||||
|
const SOCK_ENV: &str = "YANPM_AGENT_SOCK";
|
||||||
|
const SOCK_PERM_ENV: &str = "YANPM_AGENT_SOCK_PERM";
|
||||||
|
const NGINX_CONFIG_DIR_ENV: &str = "YANPM_NGINX_CONFIG_DIR";
|
||||||
|
const SOCK_GID_ENV: &str = "YANPM_AGENT_SOCK_GID";
|
||||||
|
const SOCK_DEFAULT: &str = "./yanpm-agent.sock";
|
||||||
|
const NGINX_CONFIG_DIR_DEFAULT: &str = "/etc/nginx/conf.d";
|
||||||
|
const SOCK_PERM_DEFAULT: &str = "660";
|
||||||
|
const SOCK_GID_DEFAULT: &str = "";
|
||||||
|
|
||||||
|
/// Command line arguments
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, version, about, long_about = None)]
|
||||||
|
struct Args {
|
||||||
|
/// Unix socket path to bind the agent daemon to
|
||||||
|
#[arg(short = 's', long, default_value_t = String::from(SOCK_DEFAULT), env = SOCK_ENV)]
|
||||||
|
sock: String,
|
||||||
|
|
||||||
|
/// Directory where generated nginx config files will be written
|
||||||
|
#[arg(short = 'd', long, default_value_t = String::from(NGINX_CONFIG_DIR_DEFAULT), env = NGINX_CONFIG_DIR_ENV)]
|
||||||
|
nginx_config_dir: String,
|
||||||
|
|
||||||
|
/// Permissions to set on the unix socket (in octal), e.g. 660
|
||||||
|
#[arg(long, default_value_t = String::from(SOCK_PERM_DEFAULT), env = SOCK_PERM_ENV)]
|
||||||
|
sock_perm: String,
|
||||||
|
|
||||||
|
/// GID to set on the unix socket, default: current user's primary group
|
||||||
|
#[arg(long, default_value_t = String::from(SOCK_GID_DEFAULT), env = SOCK_GID_ENV)]
|
||||||
|
sock_gid: String,
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
command: Option<SubCommand>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(clap::Subcommand, Debug)]
|
||||||
|
pub enum SubCommand {
|
||||||
|
/// Generate OpenAPI spec to file or stdout
|
||||||
|
GenerateOpenapi {
|
||||||
|
/// Output file path.
|
||||||
|
#[arg(short = 'o', long)]
|
||||||
|
output: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let subscriber = tracing_subscriber::fmt()
|
||||||
|
.with_max_level(tracing::Level::INFO)
|
||||||
|
.with_target(false)
|
||||||
|
.with_level(true)
|
||||||
|
.with_timer(tracing_subscriber::fmt::time::SystemTime)
|
||||||
|
.finish();
|
||||||
|
|
||||||
|
tracing::subscriber::set_global_default(subscriber)
|
||||||
|
.expect("Failed to set global default subscriber");
|
||||||
|
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
if let Some(cmd) = &args.command {
|
||||||
|
match cmd {
|
||||||
|
SubCommand::GenerateOpenapi { output } => {
|
||||||
|
generate_openapi_doc(&GenerateOpenapiArgs {
|
||||||
|
output: output.clone(),
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let (sock, nginx_config_dir, sock_perm, sock_gid) = get_args(&args).await?;
|
||||||
|
|
||||||
|
let path = PathBuf::from(&sock);
|
||||||
|
if let Some(dir) = path.parent() {
|
||||||
|
tokio::fs::create_dir_all(dir).await.unwrap_or_else(|err| {
|
||||||
|
error!(
|
||||||
|
"Warning: failed to create socket directory {}: {}",
|
||||||
|
dir.display(),
|
||||||
|
err
|
||||||
|
)
|
||||||
|
});
|
||||||
|
// permissive; set tighter perms in production via image/build steps
|
||||||
|
tokio::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o770))
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|err| {
|
||||||
|
error!(
|
||||||
|
"Warning: failed to set permissions on socket directory {}: {}",
|
||||||
|
dir.display(),
|
||||||
|
err
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// If an existing path exists at the socket location, ensure it's a socket
|
||||||
|
match tokio::fs::metadata(&path).await {
|
||||||
|
Ok(md) => {
|
||||||
|
use std::os::unix::fs::FileTypeExt;
|
||||||
|
if md.file_type().is_socket() {
|
||||||
|
tokio::fs::remove_file(&path).await.unwrap_or_else(|err| {
|
||||||
|
error!(
|
||||||
|
"Warning: failed to remove existing socket file {}: {}",
|
||||||
|
path.display(),
|
||||||
|
err
|
||||||
|
)
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
return Err(
|
||||||
|
format!("Socket path {} exists and is not a socket", path.display()).into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||||
|
Err(e) => {
|
||||||
|
return Err(format!("Failed to stat socket path {}: {}", path.display(), e).into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// bind using tokio's UnixListener (avoids converting a blocking std listener)
|
||||||
|
let listener = UnixListener::bind(&path).expect("Failed to bind to unix socket");
|
||||||
|
// set socket perms to sock_perm (best-effort)
|
||||||
|
if let Err(err) =
|
||||||
|
tokio::fs::set_permissions(&path, std::fs::Permissions::from_mode(sock_perm)).await
|
||||||
|
{
|
||||||
|
error!(
|
||||||
|
"Warning: failed to set permissions on socket {}: {}",
|
||||||
|
path.display(),
|
||||||
|
err
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// set socket gid to sock_gid (best-effort)
|
||||||
|
if !sock_gid.is_empty() {
|
||||||
|
use nix::unistd::{Gid, chown};
|
||||||
|
if let Err(err) = chown(
|
||||||
|
&path,
|
||||||
|
None,
|
||||||
|
Some(Gid::from_raw(
|
||||||
|
sock_gid
|
||||||
|
.parse()
|
||||||
|
.map_err(|e| format!("Failed to parse socket GID {}: {}", sock_gid, e))
|
||||||
|
.unwrap_or_else(|_| nix::unistd::getgid().as_raw()),
|
||||||
|
)),
|
||||||
|
) {
|
||||||
|
error!(
|
||||||
|
"Warning: failed to set GID on socket {}: {}",
|
||||||
|
path.display(),
|
||||||
|
err
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let scheduler = Arc::new(tokio_cron_scheduler::JobScheduler::new().await?);
|
||||||
|
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/status", get(status))
|
||||||
|
.route("/validate_and_reload", post(validate_and_reload))
|
||||||
|
.route("/validate", post(validate))
|
||||||
|
.route("/write_config", post(write_config))
|
||||||
|
.with_state(NginxService::new(scheduler.clone(), PathBuf::from(nginx_config_dir)).await?);
|
||||||
|
|
||||||
|
scheduler.clone().start().await?;
|
||||||
|
|
||||||
|
info!("Starting yanpm-daemon on unix socket: {}", sock);
|
||||||
|
axum::serve::serve(listener, app)
|
||||||
|
.await
|
||||||
|
.expect("Failed to start axum server");
|
||||||
|
|
||||||
|
info!("Shutting down yanpm-daemon");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_args(
|
||||||
|
args: &Args,
|
||||||
|
) -> Result<(String, String, u32, String), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let sock = args.sock.clone();
|
||||||
|
let nginx_config_dir = args.nginx_config_dir.clone();
|
||||||
|
let sock_perm = args.sock_perm.clone();
|
||||||
|
let sock_gid = args.sock_gid.clone();
|
||||||
|
|
||||||
|
if sock_perm.len() != 3 || !sock_perm.chars().all(|c| ('0'..='7').contains(&c)) {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidInput,
|
||||||
|
format!(
|
||||||
|
"Invalid socket permission string: {}. Must be a 3-digit octal number.",
|
||||||
|
sock_perm
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
if sock_perm.chars().last().unwrap() > '0' {
|
||||||
|
warn!(
|
||||||
|
"Socket permission string {} allows others to access the socket. This may be a security risk. Consider setting {} to a desired group and using a socket permission string that does not allow others to access the socket.",
|
||||||
|
sock_perm, SOCK_GID_ENV
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok((
|
||||||
|
sock,
|
||||||
|
nginx_config_dir,
|
||||||
|
u32::from_str_radix(&sock_perm, 8).expect("Failed to parse socket permission string"),
|
||||||
|
sock_gid,
|
||||||
|
))
|
||||||
|
}
|
||||||
45
apps/agent/src/openapi.rs
Normal file
45
apps/agent/src/openapi.rs
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
use tracing::info;
|
||||||
|
use utoipa::OpenApi;
|
||||||
|
|
||||||
|
pub mod tag {
|
||||||
|
/// nginx
|
||||||
|
pub const NGINX_TAG: &str = "Nginx Agent";
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(utoipa::OpenApi)]
|
||||||
|
#[openapi(
|
||||||
|
paths(
|
||||||
|
crate::routes::status,
|
||||||
|
crate::routes::validate,
|
||||||
|
crate::routes::validate_and_reload,
|
||||||
|
crate::routes::write_config,
|
||||||
|
),
|
||||||
|
components(
|
||||||
|
schemas(crate::routes::StatusResp),
|
||||||
|
schemas(crate::routes::ValidateAndReloadResp),
|
||||||
|
schemas(crate::routes::ValidateBody),
|
||||||
|
schemas(crate::routes::WriteConfigBody),
|
||||||
|
schemas(crate::routes::ValidateAndReloadBody),
|
||||||
|
),
|
||||||
|
tags(
|
||||||
|
(name = tag::NGINX_TAG, description = "Nginx Agent API"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
struct ApiDoc;
|
||||||
|
|
||||||
|
pub struct GenerateOpenapiArgs {
|
||||||
|
pub output: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn generate_openapi_doc(
|
||||||
|
args: &GenerateOpenapiArgs,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
info!("Generating OpenAPI documentation...");
|
||||||
|
let doc = ApiDoc::openapi();
|
||||||
|
let json = doc
|
||||||
|
.to_pretty_json()
|
||||||
|
.expect("Failed to serialize OpenAPI doc to JSON");
|
||||||
|
std::fs::write(&args.output, json).expect("Failed to write OpenAPI doc to file");
|
||||||
|
info!("OpenAPI documentation generated at {}", args.output);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
167
apps/agent/src/routes.rs
Normal file
167
apps/agent/src/routes.rs
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
use axum::Json;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::{Value, from_value};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
|
use crate::commands::NginxService;
|
||||||
|
|
||||||
|
#[derive(Serialize, utoipa::ToSchema)]
|
||||||
|
pub struct StatusResp {
|
||||||
|
pub ok: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Health check endpoint
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/status",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Status response", body = StatusResp)
|
||||||
|
),
|
||||||
|
tag = crate::openapi::tag::NGINX_TAG
|
||||||
|
)]
|
||||||
|
pub async fn status() -> impl IntoResponse {
|
||||||
|
let resp = StatusResp { ok: true };
|
||||||
|
(axum::http::StatusCode::OK, axum::Json(resp))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, utoipa::ToSchema)]
|
||||||
|
pub struct ValidateAndReloadResp {
|
||||||
|
pub rc: i32,
|
||||||
|
pub ro: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
|
pub struct ValidateBody {
|
||||||
|
config_name: String,
|
||||||
|
timestamp: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/validate",
|
||||||
|
request_body = ValidateBody,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Validation response", body = serde_json::Value)
|
||||||
|
),
|
||||||
|
tag = crate::openapi::tag::NGINX_TAG
|
||||||
|
)]
|
||||||
|
pub async fn validate(
|
||||||
|
State(nginx_controller): State<Arc<NginxService>>,
|
||||||
|
Json(payload): Json<Value>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
let params: ValidateBody = match from_value(payload) {
|
||||||
|
Ok(req) => req,
|
||||||
|
Err(e) => {
|
||||||
|
warn!("Invalid validate request: {}", e);
|
||||||
|
return (StatusCode::BAD_REQUEST).into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let resp = match nginx_controller
|
||||||
|
.validate(¶ms.config_name, params.timestamp)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(res) => res,
|
||||||
|
Err(e) => {
|
||||||
|
let resp = serde_json::json!({ "error": e.to_string() });
|
||||||
|
return (StatusCode::INTERNAL_SERVER_ERROR, axum::Json(resp)).into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
(axum::http::StatusCode::OK, axum::Json(resp)).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
|
pub struct ValidateAndReloadBody {
|
||||||
|
config_name: String,
|
||||||
|
timestamp: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/validate_and_reload",
|
||||||
|
request_body = ValidateAndReloadBody,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Validate and reload response", body = ValidateAndReloadResp)
|
||||||
|
),
|
||||||
|
tag = crate::openapi::tag::NGINX_TAG
|
||||||
|
)]
|
||||||
|
pub async fn validate_and_reload(
|
||||||
|
State(nginx_controller): State<Arc<NginxService>>,
|
||||||
|
Json(payload): Json<Value>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
let params: ValidateAndReloadBody = match from_value(payload) {
|
||||||
|
Ok(req) => req,
|
||||||
|
Err(e) => {
|
||||||
|
warn!("Invalid validate_and_reload request: {}", e);
|
||||||
|
return (StatusCode::BAD_REQUEST).into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (code, output) = match nginx_controller
|
||||||
|
.validate_and_reload(¶ms.config_name, params.timestamp)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(res) => res,
|
||||||
|
Err(e) => {
|
||||||
|
let resp = ValidateAndReloadResp {
|
||||||
|
rc: -1,
|
||||||
|
ro: e.to_string(),
|
||||||
|
};
|
||||||
|
return (StatusCode::INTERNAL_SERVER_ERROR, axum::Json(resp)).into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let resp = ValidateAndReloadResp {
|
||||||
|
rc: code,
|
||||||
|
ro: output,
|
||||||
|
};
|
||||||
|
(axum::http::StatusCode::OK, axum::Json(resp)).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
|
pub struct WriteConfigBody {
|
||||||
|
config_name: String,
|
||||||
|
timestamp: u64,
|
||||||
|
content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/write_config",
|
||||||
|
request_body = WriteConfigBody,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Write config response"),
|
||||||
|
(status = 500, description = "Internal server error", body = serde_json::Value)
|
||||||
|
),
|
||||||
|
tag = crate::openapi::tag::NGINX_TAG
|
||||||
|
)]
|
||||||
|
pub async fn write_config(
|
||||||
|
State(nginx_controller): State<Arc<NginxService>>,
|
||||||
|
Json(payload): Json<Value>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
let body: WriteConfigBody = match from_value(payload) {
|
||||||
|
Ok(req) => req,
|
||||||
|
Err(e) => {
|
||||||
|
warn!("Invalid write_config request: {}", e);
|
||||||
|
return (StatusCode::BAD_REQUEST).into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match nginx_controller
|
||||||
|
.write_config(&body.config_name, body.timestamp, &body.content)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => (),
|
||||||
|
Err(e) => {
|
||||||
|
let resp = serde_json::json!({ "error": e.to_string() });
|
||||||
|
return (StatusCode::INTERNAL_SERVER_ERROR, axum::Json(resp)).into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
(axum::http::StatusCode::OK,).into_response()
|
||||||
|
}
|
||||||
215
apps/agent/swagger.json
Normal file
215
apps/agent/swagger.json
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
{
|
||||||
|
"openapi": "3.1.0",
|
||||||
|
"info": {
|
||||||
|
"title": "yanpm-agent",
|
||||||
|
"description": "",
|
||||||
|
"license": {
|
||||||
|
"name": ""
|
||||||
|
},
|
||||||
|
"version": "0.1.0"
|
||||||
|
},
|
||||||
|
"paths": {
|
||||||
|
"/status": {
|
||||||
|
"get": {
|
||||||
|
"tags": [
|
||||||
|
"Nginx Agent"
|
||||||
|
],
|
||||||
|
"summary": "Health check endpoint",
|
||||||
|
"operationId": "status",
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Status response",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/StatusResp"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/validate": {
|
||||||
|
"post": {
|
||||||
|
"tags": [
|
||||||
|
"Nginx Agent"
|
||||||
|
],
|
||||||
|
"operationId": "validate",
|
||||||
|
"requestBody": {
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ValidateBody"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": true
|
||||||
|
},
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Validation response",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/validate_and_reload": {
|
||||||
|
"post": {
|
||||||
|
"tags": [
|
||||||
|
"Nginx Agent"
|
||||||
|
],
|
||||||
|
"operationId": "validate_and_reload",
|
||||||
|
"requestBody": {
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ValidateAndReloadBody"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": true
|
||||||
|
},
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Validate and reload response",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ValidateAndReloadResp"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/write_config": {
|
||||||
|
"post": {
|
||||||
|
"tags": [
|
||||||
|
"Nginx Agent"
|
||||||
|
],
|
||||||
|
"operationId": "write_config",
|
||||||
|
"requestBody": {
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/WriteConfigBody"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": true
|
||||||
|
},
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Write config response"
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal server error",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"components": {
|
||||||
|
"schemas": {
|
||||||
|
"StatusResp": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"ok"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"ok": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ValidateAndReloadBody": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"config_name",
|
||||||
|
"timestamp"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"config_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"timestamp": {
|
||||||
|
"type": "integer",
|
||||||
|
"format": "int64",
|
||||||
|
"minimum": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ValidateAndReloadResp": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"rc",
|
||||||
|
"ro"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"rc": {
|
||||||
|
"type": "integer",
|
||||||
|
"format": "int32"
|
||||||
|
},
|
||||||
|
"ro": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ValidateBody": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"config_name",
|
||||||
|
"timestamp"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"config_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"timestamp": {
|
||||||
|
"type": "integer",
|
||||||
|
"format": "int64",
|
||||||
|
"minimum": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"WriteConfigBody": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"config_name",
|
||||||
|
"timestamp",
|
||||||
|
"content"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"config_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"content": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"timestamp": {
|
||||||
|
"type": "integer",
|
||||||
|
"format": "int64",
|
||||||
|
"minimum": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"tags": [
|
||||||
|
{
|
||||||
|
"name": "Nginx Agent",
|
||||||
|
"description": "Nginx Agent API"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ edition = "2024"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
database = { path = "../../public/database" }
|
database = { path = "../../public/database" }
|
||||||
migration = { path = "../../public/migration" }
|
migration = { path = "../../public/migration" }
|
||||||
|
agent_client = { path = "../../public/agent-client" }
|
||||||
|
|
||||||
axum = { version = "0.8.7", features = ["form", "http1", "http2", "json", "matched-path", "original-uri", "query", "tokio", "tower-log", "tracing", "macros"] }
|
axum = { version = "0.8.7", features = ["form", "http1", "http2", "json", "matched-path", "original-uri", "query", "tokio", "tower-log", "tracing", "macros"] }
|
||||||
axum-extra = { version = "0.12.2", features = ["cookie"] }
|
axum-extra = { version = "0.12.2", features = ["cookie"] }
|
||||||
@@ -27,4 +28,11 @@ once_cell = { version = "1.21.3" }
|
|||||||
argon2 = { version = "0.5.3", features = ["std"] }
|
argon2 = { version = "0.5.3", features = ["std"] }
|
||||||
jsonwebtoken = { version = "10.2.0", features = ["rust_crypto"] }
|
jsonwebtoken = { version = "10.2.0", features = ["rust_crypto"] }
|
||||||
uuid = { version = "1.19.0", features = ["v4", "serde", "fast-rng"] }
|
uuid = { version = "1.19.0", features = ["v4", "serde", "fast-rng"] }
|
||||||
|
tower-http = { version = "0.6.8", features = ["cors"] }
|
||||||
|
reqwest = { version = "^0.12", features = ["json", "multipart", "stream"] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
|
|
||||||
|
[lints.clippy]
|
||||||
|
unwrap_used = "deny"
|
||||||
@@ -28,7 +28,7 @@ fn action(
|
|||||||
_matches: &clap::ArgMatches,
|
_matches: &clap::ArgMatches,
|
||||||
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
|
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
|
||||||
let output_path = _matches.get_one::<String>("output_path");
|
let output_path = _matches.get_one::<String>("output_path");
|
||||||
let output_path = output_path.unwrap().to_string();
|
let output_path = output_path.expect("output_path is required").to_string();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
tracing::subscriber::with_default(log::make_temporary_subscriber(), || {
|
tracing::subscriber::with_default(log::make_temporary_subscriber(), || {
|
||||||
|
|||||||
@@ -11,15 +11,8 @@ use crate::{
|
|||||||
cmd::CliCommand,
|
cmd::CliCommand,
|
||||||
configs::{ProgramSettings, get_program_settings, logging::LoggingSettings},
|
configs::{ProgramSettings, get_program_settings, logging::LoggingSettings},
|
||||||
log,
|
log,
|
||||||
routes::{self, AppService, AppState},
|
routes::{self, AppState},
|
||||||
services::{
|
services::get_app_service,
|
||||||
auth::{
|
|
||||||
authentication::{AuthenticationServiceImpl, strategies::password::PasswordStrategy},
|
|
||||||
user::UserServiceImpl,
|
|
||||||
},
|
|
||||||
server_state::ServerStateService,
|
|
||||||
settings::SettingsService,
|
|
||||||
},
|
|
||||||
tasks,
|
tasks,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -88,8 +81,10 @@ pub async fn start_server() {
|
|||||||
|
|
||||||
// build the axum app and run the server...
|
// build the axum app and run the server...
|
||||||
info!("Starting application...");
|
info!("Starting application...");
|
||||||
let mut app: Router =
|
let mut app: Router = routes::get_root_router(
|
||||||
routes::get_root_router(Arc::new(get_app_state(&db_connection, &settings)));
|
Arc::new(get_app_state(&db_connection, &settings)),
|
||||||
|
Arc::new(settings.server.cors.clone()),
|
||||||
|
);
|
||||||
|
|
||||||
if settings.server.serve_openapi {
|
if settings.server.serve_openapi {
|
||||||
info!("Enabling OpenAPI documentation endpoint at /openapi.json");
|
info!("Enabling OpenAPI documentation endpoint at /openapi.json");
|
||||||
@@ -145,19 +140,8 @@ fn get_app_state(
|
|||||||
) -> AppState {
|
) -> AppState {
|
||||||
AppState {
|
AppState {
|
||||||
database_connection: db_connection.clone(),
|
database_connection: db_connection.clone(),
|
||||||
service: Arc::new(AppService {
|
config: Arc::new(settings.clone()),
|
||||||
server_state: Arc::new(ServerStateService::new(db_connection.clone())),
|
service: Arc::new(get_app_service(db_connection, settings)),
|
||||||
settings: Arc::new(SettingsService::new(db_connection.clone())),
|
|
||||||
auth_state: routes::AuthState {
|
|
||||||
strategy: routes::AuthStrategy {
|
|
||||||
password: Arc::new(PasswordStrategy::new(db_connection.clone())),
|
|
||||||
},
|
|
||||||
authentication: Arc::new(AuthenticationServiceImpl::new(
|
|
||||||
settings.auth.jwt_secret.clone(),
|
|
||||||
)),
|
|
||||||
},
|
|
||||||
user: Arc::new(UserServiceImpl::new(db_connection.clone())),
|
|
||||||
}),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod agent;
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod database;
|
pub mod database;
|
||||||
pub mod logging;
|
pub mod logging;
|
||||||
@@ -11,6 +12,8 @@ use tracing::{debug, error};
|
|||||||
pub trait FromConfig: Sized {
|
pub trait FromConfig: Sized {
|
||||||
fn from_config(config: &Config) -> Result<Self, String>;
|
fn from_config(config: &Config) -> Result<Self, String>;
|
||||||
fn validate(&self) -> Result<(), String>;
|
fn validate(&self) -> Result<(), String>;
|
||||||
|
#[cfg(test)]
|
||||||
|
fn mock() -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -19,6 +22,7 @@ pub struct ProgramSettings {
|
|||||||
pub database: database::DatabaseSettings,
|
pub database: database::DatabaseSettings,
|
||||||
pub server: server::ServerSettings,
|
pub server: server::ServerSettings,
|
||||||
pub auth: auth::AuthSettings,
|
pub auth: auth::AuthSettings,
|
||||||
|
pub agent: agent::AgentSettings,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FromConfig for ProgramSettings {
|
impl FromConfig for ProgramSettings {
|
||||||
@@ -28,6 +32,7 @@ impl FromConfig for ProgramSettings {
|
|||||||
database: database::DatabaseSettings::from_config(_config)?,
|
database: database::DatabaseSettings::from_config(_config)?,
|
||||||
server: server::ServerSettings::from_config(_config)?,
|
server: server::ServerSettings::from_config(_config)?,
|
||||||
auth: auth::AuthSettings::from_config(_config)?,
|
auth: auth::AuthSettings::from_config(_config)?,
|
||||||
|
agent: agent::AgentSettings::from_config(_config)?,
|
||||||
};
|
};
|
||||||
config.validate()?;
|
config.validate()?;
|
||||||
Ok(config)
|
Ok(config)
|
||||||
@@ -40,6 +45,17 @@ impl FromConfig for ProgramSettings {
|
|||||||
self.auth.validate()?;
|
self.auth.validate()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn mock() -> Self {
|
||||||
|
ProgramSettings {
|
||||||
|
logging: logging::LoggingSettings::mock(),
|
||||||
|
database: database::DatabaseSettings::mock(),
|
||||||
|
server: server::ServerSettings::mock(),
|
||||||
|
auth: auth::AuthSettings::mock(),
|
||||||
|
agent: agent::AgentSettings::mock(),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_program_settings() -> ProgramSettings {
|
pub fn get_program_settings() -> ProgramSettings {
|
||||||
|
|||||||
58
apps/api/src/configs/agent.rs
Normal file
58
apps/api/src/configs/agent.rs
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
use config::Config;
|
||||||
|
use tracing::error;
|
||||||
|
|
||||||
|
use crate::configs::key::AGENT_SOCK_PATH_KEY;
|
||||||
|
|
||||||
|
use super::FromConfig;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct AgentSettings {
|
||||||
|
pub socket_path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromConfig for AgentSettings {
|
||||||
|
fn from_config(_config: &Config) -> Result<Self, String> {
|
||||||
|
Ok(AgentSettings {
|
||||||
|
socket_path: _config.get_string(AGENT_SOCK_PATH_KEY).map_err(|err| {
|
||||||
|
format!(
|
||||||
|
"Failed to get {} from configuration. Err: {}",
|
||||||
|
AGENT_SOCK_PATH_KEY, err
|
||||||
|
)
|
||||||
|
})?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate(&self) -> Result<(), String> {
|
||||||
|
// ensure socket_path exists and is readable and writable
|
||||||
|
if !std::path::Path::new(&self.socket_path).exists() {
|
||||||
|
let msg = format!("Agent socket path '{}' does not exist", self.socket_path);
|
||||||
|
error!("{}", msg);
|
||||||
|
return Err(msg);
|
||||||
|
}
|
||||||
|
if std::path::Path::new(&self.socket_path)
|
||||||
|
.metadata()
|
||||||
|
.map(|meta| {
|
||||||
|
let permissions = meta.permissions();
|
||||||
|
// Check read and write permissions for the owner
|
||||||
|
!permissions.readonly()
|
||||||
|
})
|
||||||
|
.unwrap_or(false)
|
||||||
|
{
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
let msg = format!(
|
||||||
|
"Agent socket path '{}' is not readable/writable",
|
||||||
|
self.socket_path
|
||||||
|
);
|
||||||
|
error!("{}", msg);
|
||||||
|
Err(msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn mock() -> Self {
|
||||||
|
AgentSettings {
|
||||||
|
socket_path: "/tmp/agent.sock".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -48,4 +48,13 @@ impl FromConfig for AuthSettings {
|
|||||||
fn validate(&self) -> Result<(), String> {
|
fn validate(&self) -> Result<(), String> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn mock() -> Self {
|
||||||
|
AuthSettings {
|
||||||
|
jwt_secret: Some("mock_jwt_secret".to_string()),
|
||||||
|
default_admin_username: Some("admin".to_string()),
|
||||||
|
default_admin_password: Some("password".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,4 +50,13 @@ impl FromConfig for DatabaseSettings {
|
|||||||
fn validate(&self) -> Result<(), String> {
|
fn validate(&self) -> Result<(), String> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn mock() -> Self {
|
||||||
|
DatabaseSettings {
|
||||||
|
url: "sqlite::memory:".to_string(),
|
||||||
|
max_connections: 5,
|
||||||
|
migrate_on_startup: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ pub(crate) const LOGGING_UTC_KEY: &str = "LOGGING.UTC";
|
|||||||
pub(crate) const SERVER_ADDRESS_KEY: &str = "SERVER.ADDRESS";
|
pub(crate) const SERVER_ADDRESS_KEY: &str = "SERVER.ADDRESS";
|
||||||
pub(crate) const SERVER_PORT_KEY: &str = "SERVER.PORT";
|
pub(crate) const SERVER_PORT_KEY: &str = "SERVER.PORT";
|
||||||
pub(crate) const SERVER_SERVE_OPENAPI_KEY: &str = "SERVER.SERVE_OPENAPI";
|
pub(crate) const SERVER_SERVE_OPENAPI_KEY: &str = "SERVER.SERVE_OPENAPI";
|
||||||
|
pub(crate) const SERVER_CORS_ALLOWED_ORIGINS_KEY: &str = "SERVER.CORS.ALLOWED_ORIGINS";
|
||||||
|
pub(crate) const SERVER_COOKIES_SECURE_KEY: &str = "SERVER.COOKIES.SECURE";
|
||||||
//
|
//
|
||||||
pub(crate) const DATABASE_URL_KEY: &str = "DATABASE.URL";
|
pub(crate) const DATABASE_URL_KEY: &str = "DATABASE.URL";
|
||||||
pub(crate) const DATABASE_MAX_CONNECTIONS_KEY: &str = "DATABASE.MAX_CONNECTIONS";
|
pub(crate) const DATABASE_MAX_CONNECTIONS_KEY: &str = "DATABASE.MAX_CONNECTIONS";
|
||||||
@@ -12,3 +14,5 @@ pub(crate) const DATABASE_MIGRATE_ON_STARTUP_KEY: &str = "DATABASE.MIGRATION.MIG
|
|||||||
pub(crate) const AUTH_JWT_SECRET_KEY: &str = "AUTH.JWT_SECRET";
|
pub(crate) const AUTH_JWT_SECRET_KEY: &str = "AUTH.JWT_SECRET";
|
||||||
pub(crate) const AUTH_DEFAULT_ADMIN_USERNAME_KEY: &str = "AUTH.DEFAULT_ADMIN_USERNAME";
|
pub(crate) const AUTH_DEFAULT_ADMIN_USERNAME_KEY: &str = "AUTH.DEFAULT_ADMIN_USERNAME";
|
||||||
pub(crate) const AUTH_DEFAULT_ADMIN_PASSWORD_KEY: &str = "AUTH.DEFAULT_ADMIN_PASSWORD";
|
pub(crate) const AUTH_DEFAULT_ADMIN_PASSWORD_KEY: &str = "AUTH.DEFAULT_ADMIN_PASSWORD";
|
||||||
|
//
|
||||||
|
pub(crate) const AGENT_SOCK_PATH_KEY: &str = "AGENT.SOCK.PATH";
|
||||||
|
|||||||
@@ -49,4 +49,12 @@ impl FromConfig for LoggingSettings {
|
|||||||
fn validate(&self) -> Result<(), String> {
|
fn validate(&self) -> Result<(), String> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn mock() -> Self {
|
||||||
|
LoggingSettings {
|
||||||
|
level: Level::INFO,
|
||||||
|
utc: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ use std::net::IpAddr;
|
|||||||
use config::{Config, ConfigError};
|
use config::{Config, ConfigError};
|
||||||
use tracing::warn;
|
use tracing::warn;
|
||||||
|
|
||||||
use crate::configs::key::SERVER_SERVE_OPENAPI_KEY;
|
use crate::configs::key::{
|
||||||
|
SERVER_COOKIES_SECURE_KEY, SERVER_CORS_ALLOWED_ORIGINS_KEY, SERVER_SERVE_OPENAPI_KEY,
|
||||||
|
};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
FromConfig,
|
FromConfig,
|
||||||
@@ -15,6 +17,18 @@ pub struct ServerSettings {
|
|||||||
pub address: IpAddr,
|
pub address: IpAddr,
|
||||||
pub port: u16,
|
pub port: u16,
|
||||||
pub serve_openapi: bool,
|
pub serve_openapi: bool,
|
||||||
|
pub cors: CORSSettings,
|
||||||
|
pub cookies: CookiesSettings,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct CORSSettings {
|
||||||
|
pub allowed_origins: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct CookiesSettings {
|
||||||
|
pub secure: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FromConfig for ServerSettings {
|
impl FromConfig for ServerSettings {
|
||||||
@@ -57,6 +71,42 @@ impl FromConfig for ServerSettings {
|
|||||||
);
|
);
|
||||||
DEFAULT_SERVE_OPENAPI
|
DEFAULT_SERVE_OPENAPI
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
cors: CORSSettings {
|
||||||
|
allowed_origins: _config
|
||||||
|
.get_array(SERVER_CORS_ALLOWED_ORIGINS_KEY)
|
||||||
|
.unwrap_or_else(|_| vec![])
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|val| match val.into_string() {
|
||||||
|
Ok(s) => Some(s),
|
||||||
|
Err(e) => {
|
||||||
|
warn!(
|
||||||
|
"Invalid origin in {} configuration: {}",
|
||||||
|
SERVER_CORS_ALLOWED_ORIGINS_KEY, e
|
||||||
|
);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
},
|
||||||
|
|
||||||
|
cookies: CookiesSettings {
|
||||||
|
secure: _config
|
||||||
|
.get_bool(SERVER_COOKIES_SECURE_KEY)
|
||||||
|
.inspect(|is_secure| {
|
||||||
|
if !*is_secure {
|
||||||
|
warn!("Cookie 'secure' flag is disabled; this is not recommended in production environments.");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|err| {
|
||||||
|
const DEFAULT_COOKIES_SECURE: bool = true;
|
||||||
|
warn!(
|
||||||
|
"{} not set or invalid in configuration, defaulting to {}. Error: {}",
|
||||||
|
SERVER_COOKIES_SECURE_KEY, DEFAULT_COOKIES_SECURE, err
|
||||||
|
);
|
||||||
|
DEFAULT_COOKIES_SECURE
|
||||||
|
}),
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,4 +117,17 @@ impl FromConfig for ServerSettings {
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn mock() -> Self {
|
||||||
|
ServerSettings {
|
||||||
|
address: "0.0.0.0".parse().expect("Failed to parse mock IP address"),
|
||||||
|
port: 8080,
|
||||||
|
serve_openapi: false,
|
||||||
|
cors: CORSSettings {
|
||||||
|
allowed_origins: vec![],
|
||||||
|
},
|
||||||
|
cookies: CookiesSettings { secure: true },
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,25 +6,55 @@ use std::{sync::Arc, time::Duration};
|
|||||||
use axum::{
|
use axum::{
|
||||||
BoxError, Router,
|
BoxError, Router,
|
||||||
error_handling::HandleErrorLayer,
|
error_handling::HandleErrorLayer,
|
||||||
http::{Method, StatusCode, Uri},
|
http::{HeaderValue, Method, StatusCode, Uri},
|
||||||
};
|
};
|
||||||
use tower::{ServiceBuilder, timeout::TimeoutLayer};
|
use tower::{ServiceBuilder, timeout::TimeoutLayer};
|
||||||
|
use tower_http::cors::{AllowHeaders, AllowOrigin, CorsLayer};
|
||||||
use tracing::warn;
|
use tracing::warn;
|
||||||
|
|
||||||
use crate::routes::AppState;
|
use crate::{configs::server::CORSSettings, routes::AppState};
|
||||||
|
|
||||||
pub const TIMEOUT_DURATION_SECS: u64 = 30;
|
pub const TIMEOUT_DURATION_SECS: u64 = 30;
|
||||||
|
|
||||||
pub fn apply_root_middleware(router: Router, _state: Arc<AppState>) -> Router {
|
pub fn apply_root_middleware(
|
||||||
|
router: Router,
|
||||||
|
_state: Arc<AppState>,
|
||||||
|
cors_settings: Arc<CORSSettings>,
|
||||||
|
) -> Router {
|
||||||
let timeout_layer = TimeoutLayer::new(Duration::from_secs(TIMEOUT_DURATION_SECS));
|
let timeout_layer = TimeoutLayer::new(Duration::from_secs(TIMEOUT_DURATION_SECS));
|
||||||
|
|
||||||
let service_builder = ServiceBuilder::new()
|
let service_builder = ServiceBuilder::new()
|
||||||
.layer(HandleErrorLayer::new(handle_timeout_error))
|
.layer(HandleErrorLayer::new(handle_timeout_error))
|
||||||
.layer(timeout_layer);
|
.layer(timeout_layer)
|
||||||
|
.layer(get_cors_layer(cors_settings));
|
||||||
|
|
||||||
router.layer(service_builder)
|
router.layer(service_builder)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn get_cors_layer(cors_settings: Arc<CORSSettings>) -> CorsLayer {
|
||||||
|
let mut cors_layer = CorsLayer::new()
|
||||||
|
.allow_credentials(true)
|
||||||
|
.allow_headers(AllowHeaders::mirror_request());
|
||||||
|
|
||||||
|
let allowed_origins = &cors_settings.allowed_origins;
|
||||||
|
if allowed_origins.contains(&"*".to_string()) {
|
||||||
|
cors_layer = cors_layer.allow_origin(AllowOrigin::mirror_request());
|
||||||
|
warn!(
|
||||||
|
"Wildcard origin is found in allowed origins. CORS is configured to allow requests from any origin. Only use this setting in development or if you understand the security implications."
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
for origin in allowed_origins {
|
||||||
|
if let Ok(header_value) = HeaderValue::from_str(origin) {
|
||||||
|
cors_layer = cors_layer.allow_origin(AllowOrigin::exact(header_value));
|
||||||
|
} else {
|
||||||
|
warn!("Invalid CORS origin: {}", origin);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cors_layer
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn handle_timeout_error(
|
pub async fn handle_timeout_error(
|
||||||
method: Method,
|
method: Method,
|
||||||
uri: Uri,
|
uri: Uri,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use axum::{
|
|||||||
response::Response,
|
response::Response,
|
||||||
};
|
};
|
||||||
use axum_extra::extract::cookie::CookieJar;
|
use axum_extra::extract::cookie::CookieJar;
|
||||||
|
use tracing::debug;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -25,6 +26,7 @@ pub async fn require_auth(
|
|||||||
let token = if let Some(cookie) = cookies.get(JWT_COOKIE_NAME) {
|
let token = if let Some(cookie) = cookies.get(JWT_COOKIE_NAME) {
|
||||||
cookie.value().to_string()
|
cookie.value().to_string()
|
||||||
} else {
|
} else {
|
||||||
|
debug!("No JWT cookie found. cookies: {:?}", cookies);
|
||||||
return handle_unauthenticated().await;
|
return handle_unauthenticated().await;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -9,27 +9,21 @@ use axum::{Extension, Router};
|
|||||||
use migration::sea_orm::DatabaseConnection;
|
use migration::sea_orm::DatabaseConnection;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
configs::{ProgramSettings, server::CORSSettings},
|
||||||
middlewares,
|
middlewares,
|
||||||
services::{
|
services::{
|
||||||
auth::{
|
AppService, ServiceState,
|
||||||
authentication::{AuthenticationService, strategies::password::PasswordStrategy},
|
auth::authentication::{AuthenticationService, strategies::password::PasswordStrategy},
|
||||||
user::UserService,
|
|
||||||
},
|
|
||||||
server_state::ServerStateStore,
|
|
||||||
settings::SettingsStore,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
#[allow(dead_code)]
|
|
||||||
pub database_connection: Arc<DatabaseConnection>,
|
pub database_connection: Arc<DatabaseConnection>,
|
||||||
#[allow(dead_code)]
|
|
||||||
pub service: Arc<AppService>,
|
pub service: Arc<AppService>,
|
||||||
|
pub config: Arc<ProgramSettings>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type ServiceState<T> = Arc<T>;
|
|
||||||
|
|
||||||
pub struct AuthStrategy {
|
pub struct AuthStrategy {
|
||||||
pub password: ServiceState<PasswordStrategy>,
|
pub password: ServiceState<PasswordStrategy>,
|
||||||
}
|
}
|
||||||
@@ -39,14 +33,10 @@ pub struct AuthState {
|
|||||||
pub authentication: ServiceState<dyn AuthenticationService>,
|
pub authentication: ServiceState<dyn AuthenticationService>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AppService {
|
pub fn get_root_router(
|
||||||
pub settings: ServiceState<dyn SettingsStore>,
|
state: impl Into<Arc<AppState>>,
|
||||||
pub auth_state: AuthState,
|
cors_settings: Arc<CORSSettings>,
|
||||||
pub user: ServiceState<dyn UserService>,
|
) -> Router {
|
||||||
pub server_state: ServiceState<dyn ServerStateStore>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_root_router(state: impl Into<Arc<AppState>>) -> Router {
|
|
||||||
let mut router = Router::new();
|
let mut router = Router::new();
|
||||||
let state = state.into();
|
let state = state.into();
|
||||||
|
|
||||||
@@ -54,7 +44,7 @@ pub fn get_root_router(state: impl Into<Arc<AppState>>) -> Router {
|
|||||||
.nest("/api", api::get_api_router(state.clone()))
|
.nest("/api", api::get_api_router(state.clone()))
|
||||||
.merge(view::get_view_router());
|
.merge(view::get_view_router());
|
||||||
|
|
||||||
router = middlewares::apply_root_middleware(router, state.clone());
|
router = middlewares::apply_root_middleware(router, state.clone(), cors_settings);
|
||||||
|
|
||||||
router = router.layer(Extension(state.clone()));
|
router = router.layer(Extension(state.clone()));
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,10 @@ use serde::{Deserialize, Serialize};
|
|||||||
use serde_json::{Value, from_value};
|
use serde_json::{Value, from_value};
|
||||||
use tracing::{error, warn};
|
use tracing::{error, warn};
|
||||||
|
|
||||||
use crate::routes::{AppState, api::openapi::tag::AUTH_TAG};
|
use crate::{
|
||||||
|
helpers::constants::JWT_COOKIE_NAME,
|
||||||
|
routes::{AppState, api::openapi::tag::AUTH_TAG},
|
||||||
|
};
|
||||||
|
|
||||||
/// Login request payload
|
/// Login request payload
|
||||||
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
||||||
@@ -81,9 +84,15 @@ pub async fn login(State(state): State<Arc<AppState>>, Json(payload): Json<Value
|
|||||||
.header(
|
.header(
|
||||||
SET_COOKIE,
|
SET_COOKIE,
|
||||||
format!(
|
format!(
|
||||||
"token={}; HttpOnly; Path=/; Max-Age={}; SameSite=Strict;",
|
"{}={}; HttpOnly; Path=/; Max-Age={}; SameSite=Strict;{}",
|
||||||
|
JWT_COOKIE_NAME,
|
||||||
jwt,
|
jwt,
|
||||||
claims.exp - claims.iat
|
claims.exp - claims.iat,
|
||||||
|
if state.config.server.cookies.secure {
|
||||||
|
" Secure;"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.body(Body::from(()));
|
.body(Body::from(()));
|
||||||
|
|||||||
@@ -78,6 +78,8 @@ pub async fn get_health_info(
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
|
use crate::configs::FromConfig;
|
||||||
|
use crate::services::agent_client::AgentService;
|
||||||
use crate::{
|
use crate::{
|
||||||
routes::{AppState, api::health::state::HealthState},
|
routes::{AppState, api::health::state::HealthState},
|
||||||
services::{
|
services::{
|
||||||
@@ -93,6 +95,7 @@ mod test {
|
|||||||
};
|
};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use agent_client::apis::configuration::Configuration;
|
||||||
use axum::body::to_bytes;
|
use axum::body::to_bytes;
|
||||||
use axum::{
|
use axum::{
|
||||||
Router,
|
Router,
|
||||||
@@ -112,6 +115,7 @@ mod test {
|
|||||||
|
|
||||||
let app_state = Arc::new(AppState {
|
let app_state = Arc::new(AppState {
|
||||||
database_connection: db.clone(),
|
database_connection: db.clone(),
|
||||||
|
config: Arc::new(crate::configs::ProgramSettings::mock()),
|
||||||
service: Arc::new(crate::routes::AppService {
|
service: Arc::new(crate::routes::AppService {
|
||||||
settings: Arc::new(SettingsService::new(db.clone())),
|
settings: Arc::new(SettingsService::new(db.clone())),
|
||||||
auth_state: crate::routes::AuthState {
|
auth_state: crate::routes::AuthState {
|
||||||
@@ -122,6 +126,7 @@ mod test {
|
|||||||
},
|
},
|
||||||
user: Arc::new(UserServiceImpl::new(db.clone())),
|
user: Arc::new(UserServiceImpl::new(db.clone())),
|
||||||
server_state: Arc::new(ServerStateService::new(db.clone())),
|
server_state: Arc::new(ServerStateService::new(db.clone())),
|
||||||
|
agent_client: Arc::new(AgentService::new(Configuration::default())),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -133,13 +138,21 @@ mod test {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
let response = app
|
let response = app
|
||||||
.oneshot(Request::builder().uri("/info").body(Body::empty()).unwrap())
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.uri("/info")
|
||||||
|
.body(Body::empty())
|
||||||
|
.expect("Failed to build request"),
|
||||||
|
)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let body = to_bytes(response.into_body(), 1024 * 1024).await.unwrap(); // Set limit to 1 MB
|
let body = to_bytes(response.into_body(), 1024 * 1024)
|
||||||
let health_info: HealthInfo = serde_json::from_slice(&body).unwrap();
|
.await
|
||||||
|
.expect("Failed to read response body"); // Set limit to 1 MB
|
||||||
|
let health_info: HealthInfo =
|
||||||
|
serde_json::from_slice(&body).expect("Failed to deserialize response body");
|
||||||
assert_eq!(health_info.status, STATUS_HEALTHY);
|
assert_eq!(health_info.status, STATUS_HEALTHY);
|
||||||
assert_eq!(health_info.version, env!("CARGO_PKG_VERSION"));
|
assert_eq!(health_info.version, env!("CARGO_PKG_VERSION"));
|
||||||
assert!(health_info.errors.is_none());
|
assert!(health_info.errors.is_none());
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ pub mod tag {
|
|||||||
/// Health tag constant
|
/// Health tag constant
|
||||||
pub const HEALTH_TAG: &str = "Health";
|
pub const HEALTH_TAG: &str = "Health";
|
||||||
pub const AUTH_TAG: &str = "Authentication";
|
pub const AUTH_TAG: &str = "Authentication";
|
||||||
|
pub const USER_TAG: &str = "User";
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(utoipa::OpenApi)]
|
#[derive(utoipa::OpenApi)]
|
||||||
@@ -11,16 +12,21 @@ pub mod tag {
|
|||||||
// Authentication paths
|
// Authentication paths
|
||||||
crate::routes::api::auth::login::login,
|
crate::routes::api::auth::login::login,
|
||||||
crate::routes::api::auth::init_admin::init_admin,
|
crate::routes::api::auth::init_admin::init_admin,
|
||||||
|
// User management paths
|
||||||
|
crate::routes::api::restricted::user::me::get_user_info,
|
||||||
),
|
),
|
||||||
components(
|
components(
|
||||||
schemas(crate::routes::api::health::info::HealthInfo),
|
schemas(crate::routes::api::health::info::HealthInfo),
|
||||||
// Authentication schemas
|
// Authentication schemas
|
||||||
schemas(crate::routes::api::auth::login::LoginRequest),
|
schemas(crate::routes::api::auth::login::LoginRequest),
|
||||||
schemas(crate::routes::api::auth::init_admin::AdminInitRequest),
|
schemas(crate::routes::api::auth::init_admin::AdminInitRequest),
|
||||||
|
// User management schemas
|
||||||
|
schemas(crate::routes::api::restricted::user::me::UserInfo),
|
||||||
),
|
),
|
||||||
tags(
|
tags(
|
||||||
(name = tag::HEALTH_TAG, description = "Health information API"),
|
(name = tag::HEALTH_TAG, description = "Health information API"),
|
||||||
(name = tag::AUTH_TAG, description = "Authentication API")
|
(name = tag::AUTH_TAG, description = "Authentication API"),
|
||||||
|
(name = tag::USER_TAG, description = "User management API")
|
||||||
)
|
)
|
||||||
)]
|
)]
|
||||||
pub struct ApiDoc;
|
pub struct ApiDoc;
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
pub mod user;
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use axum::Router;
|
use axum::Router;
|
||||||
@@ -6,8 +8,7 @@ use crate::{middlewares::require_auth::require_auth, routes::AppState};
|
|||||||
|
|
||||||
pub fn get_restricted_router(state: Arc<AppState>) -> Router {
|
pub fn get_restricted_router(state: Arc<AppState>) -> Router {
|
||||||
Router::new()
|
Router::new()
|
||||||
//
|
.nest("/user", user::get_user_router(state.clone()))
|
||||||
//
|
|
||||||
.layer(axum::middleware::from_fn_with_state(
|
.layer(axum::middleware::from_fn_with_state(
|
||||||
state.clone(),
|
state.clone(),
|
||||||
require_auth,
|
require_auth,
|
||||||
|
|||||||
13
apps/api/src/routes/api/restricted/user.rs
Normal file
13
apps/api/src/routes/api/restricted/user.rs
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
pub mod me;
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Router;
|
||||||
|
|
||||||
|
use crate::routes::AppState;
|
||||||
|
|
||||||
|
pub fn get_user_router(state: Arc<AppState>) -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/me", axum::routing::get(me::get_user_info))
|
||||||
|
.with_state(state)
|
||||||
|
}
|
||||||
64
apps/api/src/routes/api/restricted/user/me.rs
Normal file
64
apps/api/src/routes/api/restricted/user/me.rs
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
Extension, Json,
|
||||||
|
extract::State,
|
||||||
|
http::StatusCode,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tracing::error;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
middlewares::request_info::RequestInfo,
|
||||||
|
routes::{AppState, api::openapi::tag::USER_TAG},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// System health information
|
||||||
|
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
||||||
|
pub struct UserInfo {
|
||||||
|
/// User ID
|
||||||
|
pub id: uuid::Uuid,
|
||||||
|
/// Username
|
||||||
|
pub username: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get current user information
|
||||||
|
///
|
||||||
|
/// Returns the information of the currently authenticated user.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/user/me",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "User information retrieved successfully", body = UserInfo),
|
||||||
|
(status = 401, description = "Unauthorized"),
|
||||||
|
(status = 500, description = "Internal server error"),
|
||||||
|
),
|
||||||
|
tag = USER_TAG,
|
||||||
|
)]
|
||||||
|
pub async fn get_user_info(
|
||||||
|
State(app_state): State<Arc<AppState>>,
|
||||||
|
request_info: Extension<Arc<RequestInfo>>,
|
||||||
|
) -> Response {
|
||||||
|
let user_id = match request_info.user_id {
|
||||||
|
Some(id) => id,
|
||||||
|
None => {
|
||||||
|
error!("User ID not found in request info");
|
||||||
|
return (StatusCode::UNAUTHORIZED).into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match app_state.service.user.get_user_by_id(user_id, None).await {
|
||||||
|
Ok(user) => {
|
||||||
|
let user_info = UserInfo {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
};
|
||||||
|
(StatusCode::OK, Json(user_info)).into_response()
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
error!("Error fetching user info: {}", err);
|
||||||
|
(StatusCode::INTERNAL_SERVER_ERROR).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,54 @@
|
|||||||
|
pub mod agent_client;
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod server_state;
|
pub mod server_state;
|
||||||
pub mod settings;
|
pub mod settings;
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use ::agent_client::apis::configuration::Configuration;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
configs::ProgramSettings,
|
||||||
|
routes::{self, AuthState},
|
||||||
|
services::{
|
||||||
|
auth::{
|
||||||
|
authentication::{AuthenticationServiceImpl, strategies::password::PasswordStrategy},
|
||||||
|
user::{UserService, UserServiceImpl},
|
||||||
|
},
|
||||||
|
server_state::{ServerStateService, ServerStateStore},
|
||||||
|
settings::{SettingsService, SettingsStore},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub type ServiceState<T> = Arc<T>;
|
||||||
|
|
||||||
|
pub struct AppService {
|
||||||
|
pub settings: ServiceState<dyn SettingsStore>,
|
||||||
|
pub auth_state: AuthState,
|
||||||
|
pub user: ServiceState<dyn UserService>,
|
||||||
|
pub server_state: ServiceState<dyn ServerStateStore>,
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub agent_client: ServiceState<agent_client::AgentService>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_app_service(
|
||||||
|
db_connection: &Arc<sea_orm::DatabaseConnection>,
|
||||||
|
settings: &ProgramSettings,
|
||||||
|
) -> AppService {
|
||||||
|
AppService {
|
||||||
|
server_state: Arc::new(ServerStateService::new(db_connection.clone())),
|
||||||
|
settings: Arc::new(SettingsService::new(db_connection.clone())),
|
||||||
|
auth_state: routes::AuthState {
|
||||||
|
strategy: routes::AuthStrategy {
|
||||||
|
password: Arc::new(PasswordStrategy::new(db_connection.clone())),
|
||||||
|
},
|
||||||
|
authentication: Arc::new(AuthenticationServiceImpl::new(
|
||||||
|
settings.auth.jwt_secret.clone(),
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
user: Arc::new(UserServiceImpl::new(db_connection.clone())),
|
||||||
|
agent_client: Arc::new(agent_client::AgentService::new(Configuration::from(
|
||||||
|
settings.agent.clone(),
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
114
apps/api/src/services/agent_client.rs
Normal file
114
apps/api/src/services/agent_client.rs
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use agent_client::apis::{ApiClient, configuration::Configuration};
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
|
use crate::configs::agent::AgentSettings;
|
||||||
|
|
||||||
|
pub struct AgentService {
|
||||||
|
client: Arc<ApiClient>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<AgentSettings> for Configuration {
|
||||||
|
fn from(settings: AgentSettings) -> Self {
|
||||||
|
let mut config = Configuration::default();
|
||||||
|
let mut builder = reqwest::Client::builder();
|
||||||
|
|
||||||
|
let url = settings.socket_path;
|
||||||
|
if url.starts_with("unix://") {
|
||||||
|
builder = builder.unix_socket(url.to_string());
|
||||||
|
config.client = builder.build().expect("Failed to build reqwest client");
|
||||||
|
} else {
|
||||||
|
warn!("AgentSettings contains a non-unix socket path: {}", url);
|
||||||
|
config.base_path = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
config
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AgentService {
|
||||||
|
pub fn new(config: impl Into<Arc<Configuration>>) -> Self {
|
||||||
|
let client = ApiClient::new(config.into());
|
||||||
|
AgentService {
|
||||||
|
client: Arc::new(client),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn get_client(&self) -> Arc<ApiClient> {
|
||||||
|
Arc::clone(&self.client)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use agent_client::{
|
||||||
|
apis::{Api, nginx_agent_api::StatusSuccess},
|
||||||
|
models::StatusResp,
|
||||||
|
};
|
||||||
|
use axum::{http::StatusCode, response::Json};
|
||||||
|
use std::time::Duration;
|
||||||
|
use tempfile::tempdir;
|
||||||
|
use tokio::time::sleep;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_agent_service_creation() {
|
||||||
|
let config = Configuration::default();
|
||||||
|
let service = AgentService::new(config);
|
||||||
|
let client = service.get_client();
|
||||||
|
assert!(Arc::ptr_eq(&client, &service.client));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_agent_socket_support() {
|
||||||
|
// create temporary socket path
|
||||||
|
let dir = tempdir().expect("Failed to create temp dir");
|
||||||
|
let socket_path = dir.path().join("agent.sock");
|
||||||
|
|
||||||
|
// create axum app with a simple /status route
|
||||||
|
let app = axum::Router::new().route(
|
||||||
|
"/status",
|
||||||
|
axum::routing::get(|| async {
|
||||||
|
let result: (StatusCode, StatusResp) = (StatusCode::OK, StatusResp { ok: true });
|
||||||
|
|
||||||
|
(result.0, Json(result.1))
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// bind tokio unix listener and serve in background
|
||||||
|
let listener =
|
||||||
|
tokio::net::UnixListener::bind(&socket_path).expect("Failed to bind to unix socket");
|
||||||
|
let server_fut = axum::serve::serve(listener, app);
|
||||||
|
let _srv = tokio::spawn(async move {
|
||||||
|
let _ = server_fut.await;
|
||||||
|
});
|
||||||
|
|
||||||
|
// give server a moment to start
|
||||||
|
sleep(Duration::from_millis(50)).await;
|
||||||
|
|
||||||
|
let client: ApiClient = ApiClient::new(Arc::new(Configuration {
|
||||||
|
base_path: "http://localhost".to_string(),
|
||||||
|
client: reqwest::Client::builder()
|
||||||
|
.unix_socket(socket_path.clone())
|
||||||
|
.build()
|
||||||
|
.expect("Failed to build reqwest client"),
|
||||||
|
..Default::default()
|
||||||
|
}));
|
||||||
|
|
||||||
|
let res = client
|
||||||
|
.nginx_agent_api()
|
||||||
|
.status()
|
||||||
|
.await
|
||||||
|
.expect("Failed to get status");
|
||||||
|
let body = res.entity.expect("Response entity is missing");
|
||||||
|
|
||||||
|
assert!(res.status.is_success());
|
||||||
|
if let StatusSuccess::Status200(body) = body {
|
||||||
|
assert!(body.ok);
|
||||||
|
} else {
|
||||||
|
panic!("Unexpected response body");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ use std::{collections::HashSet, sync::Arc};
|
|||||||
use argon2::password_hash::{SaltString, rand_core::OsRng};
|
use argon2::password_hash::{SaltString, rand_core::OsRng};
|
||||||
use jsonwebtoken::{
|
use jsonwebtoken::{
|
||||||
DecodingKey, EncodingKey, Header, Validation, decode, encode,
|
DecodingKey, EncodingKey, Header, Validation, decode, encode,
|
||||||
errors::ErrorKind::{ExpiredSignature, InvalidSubject, InvalidToken},
|
errors::ErrorKind::{ExpiredSignature, InvalidSignature, InvalidSubject, InvalidToken},
|
||||||
};
|
};
|
||||||
use sea_orm::prelude::Uuid;
|
use sea_orm::prelude::Uuid;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -115,6 +115,8 @@ impl AuthenticationService for AuthenticationServiceImpl {
|
|||||||
target_sub: Option<String>,
|
target_sub: Option<String>,
|
||||||
) -> Result<Option<Claims>, ServiceError> {
|
) -> Result<Option<Claims>, ServiceError> {
|
||||||
let mut validation = Validation::default();
|
let mut validation = Validation::default();
|
||||||
|
// disable leeway for strict expiration checking
|
||||||
|
validation.leeway = 0;
|
||||||
if let Some(expected_sub) = target_sub {
|
if let Some(expected_sub) = target_sub {
|
||||||
validation.sub = Some(expected_sub);
|
validation.sub = Some(expected_sub);
|
||||||
}
|
}
|
||||||
@@ -122,7 +124,7 @@ impl AuthenticationService for AuthenticationServiceImpl {
|
|||||||
match decode::<Claims>(token, &decoding_key, &validation) {
|
match decode::<Claims>(token, &decoding_key, &validation) {
|
||||||
Ok(data) => Ok(Some(data.claims)),
|
Ok(data) => Ok(Some(data.claims)),
|
||||||
Err(err) => match *err.kind() {
|
Err(err) => match *err.kind() {
|
||||||
InvalidToken | InvalidSubject | ExpiredSignature => Ok(None),
|
InvalidToken | InvalidSubject | ExpiredSignature | InvalidSignature => Ok(None),
|
||||||
_ => Err(ServiceError::InternalError(format!(
|
_ => Err(ServiceError::InternalError(format!(
|
||||||
"JWT validation error: {}",
|
"JWT validation error: {}",
|
||||||
err
|
err
|
||||||
@@ -195,14 +197,17 @@ mod tests {
|
|||||||
let (token, _) = service
|
let (token, _) = service
|
||||||
.generate_jwt(user_id, 60)
|
.generate_jwt(user_id, 60)
|
||||||
.await
|
.await
|
||||||
.expect("generate jwt");
|
.expect("Failed to generate jwt");
|
||||||
|
|
||||||
let valid = service
|
let valid = service
|
||||||
.is_valid_jwt(&token, None)
|
.is_valid_jwt(&token, None)
|
||||||
.await
|
.await
|
||||||
.expect("validate jwt");
|
.expect("Failed to validate jwt");
|
||||||
assert!(valid.is_some(), "Generated token should be valid");
|
assert!(valid.is_some(), "Generated token should be valid");
|
||||||
let claims = service.parse_jwt(&token).await.expect("parse jwt");
|
let claims = service
|
||||||
|
.parse_jwt(&token)
|
||||||
|
.await
|
||||||
|
.expect("Failed to parse jwt");
|
||||||
assert_eq!(claims.sub, user_id.to_string());
|
assert_eq!(claims.sub, user_id.to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,10 +216,16 @@ mod tests {
|
|||||||
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
||||||
|
|
||||||
let user_id = Uuid::new_v4();
|
let user_id = Uuid::new_v4();
|
||||||
let (token, _) = service.generate_jwt(user_id, 60).await.unwrap();
|
let (token, _) = service
|
||||||
|
.generate_jwt(user_id, 60)
|
||||||
|
.await
|
||||||
|
.expect("Failed to generate jwt");
|
||||||
|
|
||||||
let other_sub = Uuid::new_v4().to_string();
|
let other_sub = Uuid::new_v4().to_string();
|
||||||
let valid = service.is_valid_jwt(&token, Some(other_sub)).await.unwrap();
|
let valid = service
|
||||||
|
.is_valid_jwt(&token, Some(other_sub))
|
||||||
|
.await
|
||||||
|
.expect("jwt is not valid");
|
||||||
assert!(
|
assert!(
|
||||||
valid.is_none(),
|
valid.is_none(),
|
||||||
"Token should be invalid for a different subject"
|
"Token should be invalid for a different subject"
|
||||||
@@ -234,10 +245,19 @@ mod tests {
|
|||||||
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
||||||
|
|
||||||
let user_id = Uuid::new_v4();
|
let user_id = Uuid::new_v4();
|
||||||
let (token, _) = service.generate_jwt(user_id, 60).await.unwrap();
|
let (token, _) = service
|
||||||
let new_token = service.refresh_jwt(&token, 120).await.unwrap();
|
.generate_jwt(user_id, 60)
|
||||||
|
.await
|
||||||
|
.expect("Failed to generate jwt");
|
||||||
|
let new_token = service
|
||||||
|
.refresh_jwt(&token, 120)
|
||||||
|
.await
|
||||||
|
.expect("Failed to refresh jwt");
|
||||||
|
|
||||||
let claims = service.parse_jwt(&new_token).await.unwrap();
|
let claims = service
|
||||||
|
.parse_jwt(&new_token)
|
||||||
|
.await
|
||||||
|
.expect("Failed to parse refreshed jwt");
|
||||||
assert_eq!(claims.sub, user_id.to_string());
|
assert_eq!(claims.sub, user_id.to_string());
|
||||||
assert_eq!(claims.exp - claims.iat, 120);
|
assert_eq!(claims.exp - claims.iat, 120);
|
||||||
}
|
}
|
||||||
@@ -247,11 +267,22 @@ mod tests {
|
|||||||
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
||||||
|
|
||||||
let user_id = Uuid::new_v4();
|
let user_id = Uuid::new_v4();
|
||||||
let (token, _) = service.generate_jwt(user_id, 1).await.unwrap();
|
let (token, claims) = service
|
||||||
|
.generate_jwt(user_id, 1)
|
||||||
|
.await
|
||||||
|
.expect("Failed to generate jwt");
|
||||||
sleep(Duration::from_secs(2)).await;
|
sleep(Duration::from_secs(2)).await;
|
||||||
|
|
||||||
let valid = service.is_valid_jwt(&token, None).await.unwrap();
|
let valid = service
|
||||||
assert!(valid.is_none(), "Token should be expired and thus invalid");
|
.is_valid_jwt(&token, None)
|
||||||
|
.await
|
||||||
|
.expect("Failed to validate jwt");
|
||||||
|
assert!(
|
||||||
|
valid.is_none(),
|
||||||
|
"Token should be expired and thus invalid. Current time: {:?}. Diff: {}",
|
||||||
|
chrono::Utc::now(),
|
||||||
|
chrono::Utc::now().timestamp() - claims.exp as i64
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -259,9 +290,15 @@ mod tests {
|
|||||||
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
let service = AuthenticationServiceImpl::new(Some("secret".to_string()));
|
||||||
|
|
||||||
let user_id = Uuid::new_v4();
|
let user_id = Uuid::new_v4();
|
||||||
let (token, _) = service.generate_jwt(user_id, 1).await.unwrap();
|
let (token, _) = service
|
||||||
|
.generate_jwt(user_id, 1)
|
||||||
|
.await
|
||||||
|
.expect("Failed to generate jwt");
|
||||||
|
|
||||||
service.invalidate_jwt(&token).await.unwrap();
|
service
|
||||||
|
.invalidate_jwt(&token)
|
||||||
|
.await
|
||||||
|
.expect("Failed to invalidate jwt");
|
||||||
|
|
||||||
// ensure entry is present
|
// ensure entry is present
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -102,6 +102,23 @@ impl PasswordStrategy {
|
|||||||
) -> Result<(), ServiceError> {
|
) -> Result<(), ServiceError> {
|
||||||
Self::is_valid_password(password).map_err(ServiceError::BadRequest)?;
|
Self::is_valid_password(password).map_err(ServiceError::BadRequest)?;
|
||||||
|
|
||||||
|
// If an identity already exists for this user/provider, treat as success.
|
||||||
|
// This also allows tests using MockDatabase to provide a query result
|
||||||
|
// for an existing identity without requiring an insert exec result.
|
||||||
|
let existing = with_conn!(&*self.connection, tx, conn, {
|
||||||
|
user_identity::Entity::find()
|
||||||
|
.filter(user_identity::Column::UserId.eq(user_id))
|
||||||
|
.filter(user_identity::Column::Provider.eq(PASSWORD_PROVIDER.to_string()))
|
||||||
|
.one(*conn)
|
||||||
|
.await?
|
||||||
|
});
|
||||||
|
|
||||||
|
if existing.is_some() {
|
||||||
|
return Err(ServiceError::BadRequest(
|
||||||
|
"Identity already exists".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
let password_hash = Argon2::default()
|
let password_hash = Argon2::default()
|
||||||
.hash_password(password.as_bytes(), &SaltString::generate(&mut OsRng))
|
.hash_password(password.as_bytes(), &SaltString::generate(&mut OsRng))
|
||||||
.map_err(|_| ServiceError::InternalError("Failed to hash password".to_string()))?
|
.map_err(|_| ServiceError::InternalError("Failed to hash password".to_string()))?
|
||||||
@@ -219,7 +236,7 @@ mod test {
|
|||||||
"CorrectPassword".as_bytes(),
|
"CorrectPassword".as_bytes(),
|
||||||
&SaltString::generate(&mut OsRng),
|
&SaltString::generate(&mut OsRng),
|
||||||
)
|
)
|
||||||
.unwrap()
|
.expect("Failed to hash password")
|
||||||
.to_string();
|
.to_string();
|
||||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||||
.append_query_results(vec![vec![user::Model {
|
.append_query_results(vec![vec![user::Model {
|
||||||
@@ -264,7 +281,7 @@ mod test {
|
|||||||
"CorrectPassword".as_bytes(),
|
"CorrectPassword".as_bytes(),
|
||||||
&SaltString::generate(&mut OsRng),
|
&SaltString::generate(&mut OsRng),
|
||||||
)
|
)
|
||||||
.unwrap()
|
.expect("Failed to hash password")
|
||||||
.to_string();
|
.to_string();
|
||||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||||
.append_query_results(vec![vec![user::Model {
|
.append_query_results(vec![vec![user::Model {
|
||||||
@@ -363,19 +380,14 @@ mod test {
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn create_identity_success() {
|
async fn create_identity_success() {
|
||||||
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||||
.append_query_results(vec![vec![user_identity::Model {
|
// No existing identity
|
||||||
id: Uuid::new_v4(),
|
.append_query_results(vec![Vec::<sea_orm::MockRow>::new()])
|
||||||
user_id: Uuid::new_v4(),
|
// Insert exec result (mock exec result for insert)
|
||||||
email: None,
|
.append_exec_results(vec![sea_orm::MockExecResult {
|
||||||
provider: PASSWORD_PROVIDER.to_string(),
|
rows_affected: 1,
|
||||||
password_hash: Some("some_hash".to_string()),
|
last_insert_id: 0,
|
||||||
metadata: None,
|
}])
|
||||||
is_revoked: false,
|
// Return inserted identity for any subsequent queries
|
||||||
revoked_at: None,
|
|
||||||
created_at: chrono::Utc::now(),
|
|
||||||
updated_at: chrono::Utc::now(),
|
|
||||||
password_changed_at: None,
|
|
||||||
}]])
|
|
||||||
.into_connection();
|
.into_connection();
|
||||||
|
|
||||||
let strategy = PasswordStrategy::new(Arc::new(db));
|
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||||
@@ -391,6 +403,30 @@ mod test {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn create_identity_existing() {
|
||||||
|
let user_id = Uuid::new_v4();
|
||||||
|
let identity = user_identity::Model {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
user_id,
|
||||||
|
email: None,
|
||||||
|
provider: PASSWORD_PROVIDER.to_string(),
|
||||||
|
password_hash: Some("hash".to_string()),
|
||||||
|
metadata: None,
|
||||||
|
is_revoked: false,
|
||||||
|
revoked_at: None,
|
||||||
|
created_at: chrono::Utc::now(),
|
||||||
|
updated_at: chrono::Utc::now(),
|
||||||
|
password_changed_at: None,
|
||||||
|
};
|
||||||
|
let db = MockDatabase::new(sea_orm::DatabaseBackend::Sqlite)
|
||||||
|
.append_query_results(vec![vec![identity]])
|
||||||
|
.into_connection();
|
||||||
|
let strategy = PasswordStrategy::new(Arc::new(db));
|
||||||
|
let result = strategy.create_identity(user_id, "ValidPass1!", None).await;
|
||||||
|
assert!(matches!(result, Err(ServiceError::BadRequest(_))));
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn update_password_not_found() {
|
async fn update_password_not_found() {
|
||||||
let user_id = Uuid::new_v4();
|
let user_id = Uuid::new_v4();
|
||||||
|
|||||||
@@ -51,7 +51,6 @@ pub trait UserService: Send + Sync {
|
|||||||
|
|
||||||
pub struct User {
|
pub struct User {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
#[allow(dead_code)] // TODO: remove when used
|
|
||||||
pub username: String,
|
pub username: String,
|
||||||
#[allow(dead_code)] // TODO: remove when used
|
#[allow(dead_code)] // TODO: remove when used
|
||||||
pub is_admin: bool,
|
pub is_admin: bool,
|
||||||
|
|||||||
@@ -11,14 +11,11 @@ use crate::errors::service_error::ServiceError;
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
pub trait SettingsStore: Send + Sync {
|
pub trait SettingsStore: Send + Sync {
|
||||||
#[allow(dead_code)] // TODO: remove when used
|
|
||||||
async fn get_setting(&self, key: &str) -> Result<String, ServiceError>;
|
async fn get_setting(&self, key: &str) -> Result<String, ServiceError>;
|
||||||
#[allow(dead_code)] // TODO: remove when used
|
|
||||||
async fn set_setting(&self, key: &str, value: String) -> Result<(), ServiceError>;
|
async fn set_setting(&self, key: &str, value: String) -> Result<(), ServiceError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct SettingsService {
|
pub struct SettingsService {
|
||||||
#[allow(dead_code)] // TODO: remove when used
|
|
||||||
connection: Arc<DatabaseConnection>,
|
connection: Arc<DatabaseConnection>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -105,6 +105,34 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"/api/user/me": {
|
||||||
|
"get": {
|
||||||
|
"tags": [
|
||||||
|
"User"
|
||||||
|
],
|
||||||
|
"summary": "Get current user information",
|
||||||
|
"description": "Returns the information of the currently authenticated user.",
|
||||||
|
"operationId": "get_user_info",
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "User information retrieved successfully",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/UserInfo"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"401": {
|
||||||
|
"description": "Unauthorized"
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal server error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"components": {
|
"components": {
|
||||||
@@ -183,6 +211,25 @@
|
|||||||
"type": "string"
|
"type": "string"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"UserInfo": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "System health information",
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"username"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "uuid",
|
||||||
|
"description": "User ID"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Username"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -194,6 +241,10 @@
|
|||||||
{
|
{
|
||||||
"name": "Authentication",
|
"name": "Authentication",
|
||||||
"description": "Authentication API"
|
"description": "Authentication API"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "User",
|
||||||
|
"description": "User management API"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,7 @@ async-trait = "0.1.89"
|
|||||||
container-simulate = { path = "../container" }
|
container-simulate = { path = "../container" }
|
||||||
migration = {path = "../../public/migration"}
|
migration = {path = "../../public/migration"}
|
||||||
shared = {path = "../../public/shared"}
|
shared = {path = "../../public/shared"}
|
||||||
testcontainers = "0.24.0"
|
testcontainers = "0.26.0"
|
||||||
tokio = { version = "1.47.0", features = ["full"] }
|
tokio = { version = "1.47.0", features = ["full"] }
|
||||||
url = "2.5.7"
|
url = "2.5.7"
|
||||||
clap = { version = "4.5.48", features = ["derive", "env"] }
|
clap = { version = "4.5.48", features = ["derive", "env"] }
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use clap::{Arg, Command};
|
use clap::{Arg, Command};
|
||||||
use container::{
|
use container::containers::{
|
||||||
|
ConfigInfoType,
|
||||||
db::{DBInfo, sqlite::SQLiteContainer},
|
db::{DBInfo, sqlite::SQLiteContainer},
|
||||||
types::ConfigInfoType,
|
|
||||||
};
|
};
|
||||||
use migration::{generate_entity, migrate_database};
|
use migration::{generate_entity, migrate_database};
|
||||||
use shared::db_type::DBType;
|
use shared::db_type::DBType;
|
||||||
@@ -54,6 +54,7 @@ fn action(
|
|||||||
for db_config in database_configs {
|
for db_config in database_configs {
|
||||||
let config = container::Config {
|
let config = container::Config {
|
||||||
database: db_config,
|
database: db_config,
|
||||||
|
agent: None,
|
||||||
};
|
};
|
||||||
let mut detached_handler = container::start_detached(&config).await;
|
let mut detached_handler = container::start_detached(&config).await;
|
||||||
match migrate_and_generate_entity(&config, &output_path).await {
|
match migrate_and_generate_entity(&config, &output_path).await {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-trait = "0.1.89"
|
async-trait = "0.1.89"
|
||||||
testcontainers = "0.24.0"
|
testcontainers = { version = "0.26.0" }
|
||||||
shared = { path = "../../public/shared" }
|
shared = { path = "../../public/shared" }
|
||||||
tokio = { version = "1.47.0", features = ["full"] }
|
tokio = { version = "1.47.0", features = ["full"] }
|
||||||
url = "2.5.7"
|
url = "2.5.7"
|
||||||
|
|||||||
40
apps/container/src/containers.rs
Normal file
40
apps/container/src/containers.rs
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
pub mod agent;
|
||||||
|
pub mod db;
|
||||||
|
|
||||||
|
use std::{pin::Pin, sync::Arc};
|
||||||
|
|
||||||
|
use testcontainers::{ContainerAsync, GenericImage, TestcontainersError};
|
||||||
|
|
||||||
|
use crate::containers::{
|
||||||
|
agent::AgentContainerInfo,
|
||||||
|
db::{ContainerizedDBInfo, PreExistingDBInfo},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub type UnStartedContainer =
|
||||||
|
Pin<Box<dyn Future<Output = Result<ContainerAsync<GenericImage>, TestcontainersError>> + Send>>;
|
||||||
|
|
||||||
|
pub type AgentConfigInfoType = ConfigInfoType<AgentContainerInfo, ()>;
|
||||||
|
|
||||||
|
pub type DBConfigInfoType = ConfigInfoType<ContainerizedDBInfo, PreExistingDBInfo>;
|
||||||
|
|
||||||
|
pub trait WithContainer {
|
||||||
|
fn container(&self) -> &Arc<ContainerAsync<GenericImage>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait WithoutContainer {
|
||||||
|
fn on_delete(&self);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WithoutContainer for () {
|
||||||
|
fn on_delete(&self) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum ConfigInfoType<T, U>
|
||||||
|
where
|
||||||
|
T: WithContainer,
|
||||||
|
U: WithoutContainer,
|
||||||
|
{
|
||||||
|
Containerized(T),
|
||||||
|
PreExisting(U),
|
||||||
|
}
|
||||||
115
apps/container/src/containers/agent.rs
Normal file
115
apps/container/src/containers/agent.rs
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
use std::{error::Error, sync::Arc};
|
||||||
|
use testcontainers::{
|
||||||
|
ContainerAsync, GenericBuildableImage, GenericImage, ImageExt,
|
||||||
|
core::{AccessMode, BuildImageOptions, ContainerPort, Mount, WaitFor},
|
||||||
|
runners::{AsyncBuilder, AsyncRunner},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{WithContainer, containers::UnStartedContainer};
|
||||||
|
|
||||||
|
pub const SOCK_NAME: &str = "yanpm-agent.sock";
|
||||||
|
const SOCK_FOLDER: &str = "/var/run/yanpm";
|
||||||
|
const NGINX_CONFIG_DIR: &str = "/etc/nginx/conf.d";
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AgentContainerConfig {
|
||||||
|
pub image: String,
|
||||||
|
pub tag: String,
|
||||||
|
pub container_name: String,
|
||||||
|
pub dockerfile_path: String,
|
||||||
|
pub force_build: bool,
|
||||||
|
pub agent_config: AgentConfig,
|
||||||
|
pub nginx_config: NginxConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AgentContainerInfo {
|
||||||
|
pub container: Arc<ContainerAsync<GenericImage>>,
|
||||||
|
pub config: AgentContainerConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WithContainer for AgentContainerInfo {
|
||||||
|
fn container(&self) -> &Arc<ContainerAsync<GenericImage>> {
|
||||||
|
&self.container
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AgentConfig {
|
||||||
|
pub sock_folder: String, // path to be mounted to host for unix socket
|
||||||
|
pub nginx_config_dir: String, // path to be mounted to host for nginx config files, only the agent generated folder will be mounted
|
||||||
|
pub sock_perm: u32, // permissions to set on the unix socket
|
||||||
|
pub sock_gid: String, // GID to set on the unix socket
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct NginxConfig {
|
||||||
|
pub expose_http: bool,
|
||||||
|
pub expose_https: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AgentContainerConfig {
|
||||||
|
pub fn new(
|
||||||
|
image: String,
|
||||||
|
tag: String,
|
||||||
|
container_name: String,
|
||||||
|
dockerfile_path: String,
|
||||||
|
force_build: bool,
|
||||||
|
// agent configs
|
||||||
|
agent_config: AgentConfig,
|
||||||
|
nginx_config: NginxConfig,
|
||||||
|
) -> Self {
|
||||||
|
AgentContainerConfig {
|
||||||
|
image,
|
||||||
|
tag,
|
||||||
|
container_name,
|
||||||
|
dockerfile_path,
|
||||||
|
force_build,
|
||||||
|
// default agent configs
|
||||||
|
agent_config,
|
||||||
|
nginx_config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_unstarted_container(&self) -> Result<UnStartedContainer, Box<dyn Error>> {
|
||||||
|
let mut image = GenericBuildableImage::new(&self.image, &self.tag)
|
||||||
|
.with_dockerfile(&self.dockerfile_path)
|
||||||
|
.build_image_with(BuildImageOptions::new().with_skip_if_exists(!self.force_build))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if self.nginx_config.expose_http {
|
||||||
|
image = image.with_exposed_port(ContainerPort::Tcp(80));
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.nginx_config.expose_https {
|
||||||
|
image = image.with_exposed_port(ContainerPort::Tcp(443));
|
||||||
|
}
|
||||||
|
|
||||||
|
image = image.with_wait_for(WaitFor::message_on_either_std("Starting yanpm-daemon on"));
|
||||||
|
|
||||||
|
Ok(image
|
||||||
|
.with_container_name(self.container_name.clone())
|
||||||
|
.with_env_var("YANPM_AGENT_SOCK", format!("{}/{}", SOCK_FOLDER, SOCK_NAME))
|
||||||
|
.with_env_var("YANPM_NGINX_CONFIG_DIR", NGINX_CONFIG_DIR.to_string())
|
||||||
|
.with_env_var(
|
||||||
|
"YANPM_AGENT_SOCK_PERM",
|
||||||
|
self.agent_config.sock_perm.to_string(),
|
||||||
|
)
|
||||||
|
.with_env_var("YANPM_AGENT_SOCK_GID", self.agent_config.sock_gid.clone())
|
||||||
|
.with_mount(
|
||||||
|
Mount::bind_mount(
|
||||||
|
self.agent_config.sock_folder.clone(),
|
||||||
|
SOCK_FOLDER.to_string(),
|
||||||
|
)
|
||||||
|
.with_access_mode(AccessMode::ReadWrite),
|
||||||
|
)
|
||||||
|
.with_mount(
|
||||||
|
Mount::bind_mount(
|
||||||
|
self.agent_config.nginx_config_dir.clone(),
|
||||||
|
NGINX_CONFIG_DIR.to_string(),
|
||||||
|
)
|
||||||
|
.with_access_mode(AccessMode::ReadWrite),
|
||||||
|
)
|
||||||
|
.start())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,18 +5,15 @@ pub mod sqlite;
|
|||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use shared::db_type::DBType;
|
use shared::db_type::DBType;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::future::Future;
|
use std::sync::Arc;
|
||||||
use std::{pin::Pin, sync::Arc};
|
|
||||||
use url::Host;
|
use url::Host;
|
||||||
|
|
||||||
use testcontainers::{ContainerAsync, GenericImage, TestcontainersError};
|
use testcontainers::{ContainerAsync, GenericImage};
|
||||||
|
|
||||||
use crate::{ConfigInfoType, WithContainer, WithoutContainer};
|
use crate::{
|
||||||
|
WithContainer, WithoutContainer,
|
||||||
pub type UnStartedContainer =
|
containers::{DBConfigInfoType, UnStartedContainer},
|
||||||
Pin<Box<dyn Future<Output = Result<ContainerAsync<GenericImage>, TestcontainersError>> + Send>>;
|
};
|
||||||
|
|
||||||
pub type DBConfigInfoType = ConfigInfoType<ContainerizedDBInfo, PreExistingDBInfo>;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct PreExistingDBInfo {
|
pub struct PreExistingDBInfo {
|
||||||
@@ -9,7 +9,7 @@ pub struct OptionalContainerConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ContainerConfig {
|
pub struct DatabaseContainerConfig {
|
||||||
pub image: String,
|
pub image: String,
|
||||||
pub tag: String,
|
pub tag: String,
|
||||||
pub container_name: String,
|
pub container_name: String,
|
||||||
@@ -19,8 +19,8 @@ pub struct ContainerConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl OptionalContainerConfig {
|
impl OptionalContainerConfig {
|
||||||
pub fn fill_with(&self, other: &ContainerConfig) -> ContainerConfig {
|
pub fn fill_with(&self, other: &DatabaseContainerConfig) -> DatabaseContainerConfig {
|
||||||
ContainerConfig {
|
DatabaseContainerConfig {
|
||||||
image: self.image.clone().unwrap_or_else(|| other.image.clone()),
|
image: self.image.clone().unwrap_or_else(|| other.image.clone()),
|
||||||
tag: self.tag.clone().unwrap_or_else(|| other.tag.clone()),
|
tag: self.tag.clone().unwrap_or_else(|| other.tag.clone()),
|
||||||
container_name: self
|
container_name: self
|
||||||
@@ -9,14 +9,17 @@ use testcontainers::{
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
ConfigInfoType,
|
ConfigInfoType,
|
||||||
db::{
|
containers::{
|
||||||
ContainerizedDBInfo, DBConfigInfoType, DBInfo, UnStartedContainer,
|
UnStartedContainer,
|
||||||
config::{ContainerConfig, OptionalContainerConfig},
|
db::{
|
||||||
|
ContainerizedDBInfo, DBConfigInfoType, DBInfo,
|
||||||
|
config::{DatabaseContainerConfig, OptionalContainerConfig},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn get_default_config() -> ContainerConfig {
|
pub fn get_default_config() -> DatabaseContainerConfig {
|
||||||
ContainerConfig {
|
DatabaseContainerConfig {
|
||||||
container_name: "yanpm-postgres".to_string(),
|
container_name: "yanpm-postgres".to_string(),
|
||||||
database_name: "postgres".to_string(),
|
database_name: "postgres".to_string(),
|
||||||
user: "postgres".to_string(),
|
user: "postgres".to_string(),
|
||||||
@@ -27,7 +30,7 @@ pub fn get_default_config() -> ContainerConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct PostgreSQLContainer {
|
pub struct PostgreSQLContainer {
|
||||||
pub config: ContainerConfig,
|
pub config: DatabaseContainerConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -53,7 +56,7 @@ impl DBInfo<OptionalContainerConfig> for PostgreSQLContainer {
|
|||||||
);
|
);
|
||||||
|
|
||||||
ConfigInfoType::Containerized(ContainerizedDBInfo {
|
ConfigInfoType::Containerized(ContainerizedDBInfo {
|
||||||
db_type: crate::db::DBType::PostgreSQL,
|
db_type: crate::containers::db::DBType::PostgreSQL,
|
||||||
container: Arc::new(pg_container),
|
container: Arc::new(pg_container),
|
||||||
container_name: self.config.container_name.clone(),
|
container_name: self.config.container_name.clone(),
|
||||||
database_name: self.config.database_name.clone(),
|
database_name: self.config.database_name.clone(),
|
||||||
@@ -4,7 +4,7 @@ use async_trait::async_trait;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
ConfigInfoType,
|
ConfigInfoType,
|
||||||
db::{DBConfigInfoType, DBInfo, PreExistingDBInfo, UnStartedContainer},
|
containers::db::{DBConfigInfoType, DBInfo, PreExistingDBInfo, UnStartedContainer},
|
||||||
util::to_absolute_path,
|
util::to_absolute_path,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ impl DBInfo<OptionalContainerConfig> for SQLiteContainer {
|
|||||||
.expect("Failed to create SQLite database file");
|
.expect("Failed to create SQLite database file");
|
||||||
//
|
//
|
||||||
ConfigInfoType::PreExisting(PreExistingDBInfo {
|
ConfigInfoType::PreExisting(PreExistingDBInfo {
|
||||||
db_type: crate::db::DBType::SQLite,
|
db_type: crate::containers::db::DBType::SQLite,
|
||||||
url: sqlite_url,
|
url: sqlite_url,
|
||||||
on_delete: {
|
on_delete: {
|
||||||
let db_path = self.get_db_absolute_path();
|
let db_path = self.get_db_absolute_path();
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
use shared::db_type::DBType;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub enum EnvFileType {
|
pub enum EnvFileType {
|
||||||
DotEnv,
|
DotEnv,
|
||||||
@@ -11,25 +9,20 @@ pub enum EnvFileType {
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct EnvFile {
|
pub struct EnvFile {
|
||||||
pub file_type: EnvFileType,
|
pub file_type: EnvFileType,
|
||||||
pub db_type: DBType,
|
|
||||||
pub db_url: String,
|
|
||||||
//
|
//
|
||||||
buffer: serde_json::Value,
|
buffer: serde_json::Value,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EnvFile {
|
impl EnvFile {
|
||||||
pub fn new(file_type: EnvFileType, db_type: DBType, db_url: String) -> Self {
|
pub fn new(file_type: EnvFileType) -> Self {
|
||||||
let mut env_file = EnvFile {
|
EnvFile {
|
||||||
file_type,
|
file_type,
|
||||||
db_type,
|
|
||||||
db_url,
|
|
||||||
buffer: serde_json::Value::Object(serde_json::Map::new()),
|
buffer: serde_json::Value::Object(serde_json::Map::new()),
|
||||||
};
|
}
|
||||||
|
}
|
||||||
|
|
||||||
env_file._write_line_buffer("DATABASE__TYPE", &env_file.db_type.to_string());
|
pub fn write_line(&mut self, key: &str, value: &str) {
|
||||||
env_file._write_line_buffer("DATABASE__URL", &env_file.db_url.to_string());
|
self._write_line_buffer(key, value);
|
||||||
|
|
||||||
env_file
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn write(&mut self, stream: &mut dyn Write, with_prefix: bool) {
|
pub fn write(&mut self, stream: &mut dyn Write, with_prefix: bool) {
|
||||||
@@ -127,12 +120,10 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_env_file_write_yaml() {
|
fn test_env_file_write_yaml() {
|
||||||
let mut env_file_nested = EnvFile::new(
|
let mut env_file_nested = EnvFile::new(EnvFileType::Yaml);
|
||||||
EnvFileType::Yaml,
|
|
||||||
DBType::SQLite,
|
|
||||||
"mysql://user:pass@localhost/db".to_string(),
|
|
||||||
);
|
|
||||||
|
|
||||||
|
env_file_nested.write_line("DATABASE__TYPE", "SQLite");
|
||||||
|
env_file_nested.write_line("DATABASE__URL", "mysql://user:pass@localhost/db");
|
||||||
let mut output_stream = Vec::new();
|
let mut output_stream = Vec::new();
|
||||||
env_file_nested.write(&mut output_stream, false);
|
env_file_nested.write(&mut output_stream, false);
|
||||||
let output_string = String::from_utf8(output_stream).unwrap();
|
let output_string = String::from_utf8(output_stream).unwrap();
|
||||||
@@ -146,11 +137,9 @@ DATABASE:
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_env_file_write_env() {
|
fn test_env_file_write_env() {
|
||||||
let mut env_file_nested = EnvFile::new(
|
let mut env_file_nested = EnvFile::new(EnvFileType::DotEnv);
|
||||||
EnvFileType::DotEnv,
|
env_file_nested.write_line("DATABASE__TYPE", "PostgreSQL");
|
||||||
DBType::PostgreSQL,
|
env_file_nested.write_line("DATABASE__URL", "postgres://user:pass@localhost/db");
|
||||||
"postgres://user:pass@localhost/db".to_string(),
|
|
||||||
);
|
|
||||||
let mut output_stream = Vec::new();
|
let mut output_stream = Vec::new();
|
||||||
env_file_nested.write(&mut output_stream, true);
|
env_file_nested.write(&mut output_stream, true);
|
||||||
let output_string = String::from_utf8(output_stream).unwrap();
|
let output_string = String::from_utf8(output_stream).unwrap();
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
pub mod db;
|
pub mod containers;
|
||||||
mod env;
|
mod env;
|
||||||
pub mod types;
|
|
||||||
mod util;
|
mod util;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
db::DBConfigInfoType,
|
containers::{
|
||||||
types::{ConfigInfoType, WithContainer, WithoutContainer},
|
AgentConfigInfoType, ConfigInfoType, DBConfigInfoType, WithContainer, WithoutContainer,
|
||||||
|
},
|
||||||
util::{
|
util::{
|
||||||
await_termination_signal, remove_file_if_exists, stop_container, to_absolute_path,
|
await_termination_signal, remove_file_if_exists, stop_container, to_absolute_path,
|
||||||
write_env_files,
|
write_env_files,
|
||||||
@@ -15,6 +15,7 @@ use crate::{
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub database: DBConfigInfoType,
|
pub database: DBConfigInfoType,
|
||||||
|
pub agent: Option<AgentConfigInfoType>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// relative to the pwd
|
// relative to the pwd
|
||||||
@@ -56,26 +57,29 @@ impl<'a> Drop for DetachedHandle<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn start(config: &Config) {
|
async fn start(config: &Config) {
|
||||||
let db_config = &config.database;
|
|
||||||
//
|
|
||||||
// write the config files for the api server and database client
|
// write the config files for the api server and database client
|
||||||
println!("Writing config files...");
|
println!("Writing config files...");
|
||||||
write_env_files(db_config);
|
write_env_files(&config.database, &config.agent);
|
||||||
println!("Config files written to:");
|
println!("Config files written to:");
|
||||||
println!(" - {}", to_absolute_path(API_CONFIG_PATH).display());
|
println!(" - {}", to_absolute_path(API_CONFIG_PATH).display());
|
||||||
println!(" - {}", to_absolute_path(DB_CONFIG_PATH).display());
|
println!(" - {}", to_absolute_path(DB_CONFIG_PATH).display());
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn stop(config: &Config) {
|
async fn stop(config: &Config) {
|
||||||
let db_config = &config.database;
|
|
||||||
// stop the container
|
// stop the container
|
||||||
println!("Stopping container...");
|
println!("Stopping container...");
|
||||||
stop_container(db_config, "database".to_string()).await;
|
println!("Stopping database container...");
|
||||||
|
stop_container(&config.database, "database".to_string()).await;
|
||||||
|
if let Some(agent) = &config.agent {
|
||||||
|
println!("Stopping agent container...");
|
||||||
|
stop_container(agent, "agent".to_string()).await;
|
||||||
|
}
|
||||||
|
println!("Container stopped.");
|
||||||
// remove the generated config file
|
// remove the generated config file
|
||||||
println!("Removing generated config file...");
|
println!("Removing generated config file...");
|
||||||
remove_file_if_exists(DB_CONFIG_PATH);
|
remove_file_if_exists(DB_CONFIG_PATH);
|
||||||
remove_file_if_exists(API_CONFIG_PATH);
|
remove_file_if_exists(API_CONFIG_PATH);
|
||||||
println!("Container stopped.");
|
println!("Generated config files removed.");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start_attached(config: &Config) {
|
pub async fn start_attached(config: &Config) {
|
||||||
|
|||||||
@@ -1,8 +1,15 @@
|
|||||||
use clap::Parser;
|
use std::sync::Arc;
|
||||||
use container::Config;
|
|
||||||
use container::start_attached;
|
|
||||||
|
|
||||||
use container::db::DBInfo;
|
use clap::Parser;
|
||||||
|
use container::{
|
||||||
|
Config,
|
||||||
|
containers::{
|
||||||
|
ConfigInfoType,
|
||||||
|
agent::{AgentConfig, AgentContainerConfig, AgentContainerInfo, NginxConfig},
|
||||||
|
db::DBInfo,
|
||||||
|
},
|
||||||
|
start_attached,
|
||||||
|
};
|
||||||
|
|
||||||
/// Command line arguments
|
/// Command line arguments
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
@@ -11,17 +18,63 @@ struct Args {
|
|||||||
/// Database type to use: 'postgres' or 'sqlite'. Can also be set with DB_TYPE env var.
|
/// Database type to use: 'postgres' or 'sqlite'. Can also be set with DB_TYPE env var.
|
||||||
#[arg(long, default_value = "sqlite", env = "DB_TYPE")]
|
#[arg(long, default_value = "sqlite", env = "DB_TYPE")]
|
||||||
db_type: String,
|
db_type: String,
|
||||||
|
|
||||||
|
// agent related
|
||||||
|
/// agent image name
|
||||||
|
#[arg(long, default_value = "yanpm/agent", env = "AGENT_IMAGE_NAME")]
|
||||||
|
agent_image: String,
|
||||||
|
/// agent image tag
|
||||||
|
#[arg(long, default_value = "latest", env = "AGENT_IMAGE_TAG")]
|
||||||
|
agent_image_tag: String,
|
||||||
|
/// force build agent image
|
||||||
|
#[arg(long, default_value_t = false, env = "AGENT_FORCE_BUILD")]
|
||||||
|
agent_force_build: bool,
|
||||||
|
/// dockerfile path for building agent image
|
||||||
|
#[arg(long, env = "AGENT_DOCKERFILE_PATH", required = false)]
|
||||||
|
agent_dockerfile_path: Option<String>,
|
||||||
|
/// host's location to mount nginx config files folder generated by the agent
|
||||||
|
#[arg(long, env = "AGENT_NGINX_CONFIG_DIR", required = false)]
|
||||||
|
agent_nginx_config_dir: Option<String>,
|
||||||
|
/// host's location folder to mount the unix socket files
|
||||||
|
#[arg(long, env = "AGENT_SOCK_PATH", required = false)]
|
||||||
|
agent_sock_path: Option<String>,
|
||||||
|
/// socket permissions to set on the unix socket
|
||||||
|
#[arg(long, default_value = "660", env = "AGENT_SOCK_PERM", required = false)]
|
||||||
|
agent_sock_perm: u32,
|
||||||
|
/// socket GID to set on the unix socket
|
||||||
|
#[arg(long, default_value = "", env = "AGENT_SOCK_GID", required = false)]
|
||||||
|
agent_sock_gid: String,
|
||||||
|
/// nginx expose http port
|
||||||
|
#[arg(
|
||||||
|
long,
|
||||||
|
default_value_t = true,
|
||||||
|
env = "AGENT_NGINX_EXPOSE_HTTP",
|
||||||
|
required = false
|
||||||
|
)]
|
||||||
|
agent_nginx_expose_http: bool,
|
||||||
|
/// nginx expose https port
|
||||||
|
#[arg(
|
||||||
|
long,
|
||||||
|
default_value_t = false,
|
||||||
|
env = "AGENT_NGINX_EXPOSE_HTTPS",
|
||||||
|
required = false
|
||||||
|
)]
|
||||||
|
agent_nginx_expose_https: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ParsedArgs {
|
||||||
|
db_type: String,
|
||||||
|
agent_container_config: Option<AgentContainerConfig>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
// Parse command line arguments and environment variables
|
let args = parse_args().await;
|
||||||
let args = Args::parse();
|
|
||||||
|
|
||||||
println!("Starting container with database type: {}", args.db_type);
|
println!("Starting container with database type: {}", args.db_type);
|
||||||
let db_config = match args.db_type.to_lowercase().as_str() {
|
let db_config = match args.db_type.to_lowercase().as_str() {
|
||||||
"postgres" | "pg" | "pgsql" => {
|
"postgres" | "pg" | "pgsql" => {
|
||||||
use container::db::postgresql::PostgreSQLContainer;
|
use container::containers::db::postgresql::PostgreSQLContainer;
|
||||||
println!("Using PostgreSQL database");
|
println!("Using PostgreSQL database");
|
||||||
PostgreSQLContainer::new(None)
|
PostgreSQLContainer::new(None)
|
||||||
.await
|
.await
|
||||||
@@ -30,7 +83,7 @@ async fn main() {
|
|||||||
}
|
}
|
||||||
"sqlite" | "sql" => {
|
"sqlite" | "sql" => {
|
||||||
println!("Using SQLite database");
|
println!("Using SQLite database");
|
||||||
use container::db::sqlite::SQLiteContainer;
|
use container::containers::db::sqlite::SQLiteContainer;
|
||||||
SQLiteContainer::new(None)
|
SQLiteContainer::new(None)
|
||||||
.await
|
.await
|
||||||
.get_db_container_config_info()
|
.get_db_container_config_info()
|
||||||
@@ -43,11 +96,98 @@ async fn main() {
|
|||||||
};
|
};
|
||||||
println!("Database configuration obtained.");
|
println!("Database configuration obtained.");
|
||||||
|
|
||||||
|
let agent_container = if let Some(agent_config) = &args.agent_container_config {
|
||||||
|
println!(
|
||||||
|
"Agent container will be used with socket folder: {} and nginx config dir: {}",
|
||||||
|
agent_config.agent_config.sock_folder, agent_config.agent_config.nginx_config_dir
|
||||||
|
);
|
||||||
|
Some(agent_config.get_unstarted_container().await)
|
||||||
|
} else {
|
||||||
|
println!("No agent container configuration provided, skipping agent setup.");
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
let config = Config {
|
let config = Config {
|
||||||
database: db_config,
|
database: db_config,
|
||||||
|
agent: match agent_container {
|
||||||
|
Some(Ok(container)) => Some(ConfigInfoType::Containerized(AgentContainerInfo {
|
||||||
|
container: Arc::new(container.await.expect("Failed to start agent container")),
|
||||||
|
config: args.agent_container_config.expect("Invalid config state"),
|
||||||
|
})),
|
||||||
|
Some(Err(e)) => {
|
||||||
|
eprintln!("Failed to set up agent container: {}", e);
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
println!("Starting container...");
|
println!("Starting container...");
|
||||||
start_attached(&config).await;
|
start_attached(&config).await;
|
||||||
println!("Container stopped. Exiting...");
|
println!("Container stopped. Exiting...");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn parse_args() -> ParsedArgs {
|
||||||
|
// Parse command line arguments and environment variables
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
// if any required args are missing, do not start agent
|
||||||
|
let dockerfile_path = match args.agent_dockerfile_path {
|
||||||
|
None => {
|
||||||
|
println!("Agent dockerfile path not provided, skipping agent setup.");
|
||||||
|
return ParsedArgs {
|
||||||
|
db_type: args.db_type,
|
||||||
|
agent_container_config: None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Some(path) => path,
|
||||||
|
};
|
||||||
|
|
||||||
|
let time = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_secs();
|
||||||
|
|
||||||
|
let agent_config = AgentConfig {
|
||||||
|
sock_folder: match args.agent_sock_path {
|
||||||
|
None => {
|
||||||
|
// create a temp dir for the socket path
|
||||||
|
let temp_dir = std::env::temp_dir().join(format!("yanpm-agent-sock-{}", time));
|
||||||
|
std::fs::create_dir_all(&temp_dir)
|
||||||
|
.expect("Failed to create temp dir for agent socket");
|
||||||
|
temp_dir.to_string_lossy().to_string()
|
||||||
|
}
|
||||||
|
Some(path) => path,
|
||||||
|
},
|
||||||
|
nginx_config_dir: match args.agent_nginx_config_dir {
|
||||||
|
None => {
|
||||||
|
// create a temp dir for the nginx config dir
|
||||||
|
let temp_dir =
|
||||||
|
std::env::temp_dir().join(format!("yanpm-agent-nginx-configs-{}", time));
|
||||||
|
std::fs::create_dir_all(&temp_dir)
|
||||||
|
.expect("Failed to create temp dir for agent nginx configs");
|
||||||
|
temp_dir.to_string_lossy().to_string()
|
||||||
|
}
|
||||||
|
Some(path) => path,
|
||||||
|
},
|
||||||
|
sock_perm: args.agent_sock_perm,
|
||||||
|
sock_gid: args.agent_sock_gid.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
ParsedArgs {
|
||||||
|
db_type: args.db_type,
|
||||||
|
agent_container_config: Some(AgentContainerConfig {
|
||||||
|
// TODO: allow customization of these fields via CLI args
|
||||||
|
image: args.agent_image,
|
||||||
|
tag: args.agent_image_tag,
|
||||||
|
container_name: format!("yanpm-agent-container-{}", time),
|
||||||
|
dockerfile_path,
|
||||||
|
force_build: args.agent_force_build,
|
||||||
|
agent_config,
|
||||||
|
nginx_config: NginxConfig {
|
||||||
|
expose_http: args.agent_nginx_expose_http,
|
||||||
|
expose_https: args.agent_nginx_expose_https,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use testcontainers::{ContainerAsync, GenericImage};
|
|
||||||
|
|
||||||
pub trait WithContainer {
|
|
||||||
fn container(&self) -> &Arc<ContainerAsync<GenericImage>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait WithoutContainer {
|
|
||||||
fn on_delete(&self);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub enum ConfigInfoType<T, U>
|
|
||||||
where
|
|
||||||
T: WithContainer,
|
|
||||||
U: WithoutContainer,
|
|
||||||
{
|
|
||||||
Containerized(T),
|
|
||||||
PreExisting(U),
|
|
||||||
}
|
|
||||||
@@ -4,9 +4,11 @@ use tokio::signal::unix::{SignalKind, signal};
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
API_CONFIG_PATH, DB_CONFIG_PATH,
|
API_CONFIG_PATH, DB_CONFIG_PATH,
|
||||||
db::DBConfigInfoType,
|
containers::{
|
||||||
|
AgentConfigInfoType, ConfigInfoType, DBConfigInfoType, WithContainer, WithoutContainer,
|
||||||
|
agent::SOCK_NAME,
|
||||||
|
},
|
||||||
env::{self, EnvFile},
|
env::{self, EnvFile},
|
||||||
types::{ConfigInfoType, WithContainer, WithoutContainer},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// relative to the current working directory
|
// relative to the current working directory
|
||||||
@@ -20,7 +22,7 @@ pub fn to_absolute_path(path: &str) -> PathBuf {
|
|||||||
.clean()
|
.clean()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn write_env_files(db_config: &DBConfigInfoType) {
|
pub fn write_env_files(db_config: &DBConfigInfoType, agent_config: &Option<AgentConfigInfoType>) {
|
||||||
let api_config_path_absolute = to_absolute_path(API_CONFIG_PATH);
|
let api_config_path_absolute = to_absolute_path(API_CONFIG_PATH);
|
||||||
let db_config_path_absolute = to_absolute_path(DB_CONFIG_PATH);
|
let db_config_path_absolute = to_absolute_path(DB_CONFIG_PATH);
|
||||||
|
|
||||||
@@ -29,10 +31,27 @@ pub fn write_env_files(db_config: &DBConfigInfoType) {
|
|||||||
DBConfigInfoType::PreExisting(config) => (config.db_type.clone(), config.url.clone()),
|
DBConfigInfoType::PreExisting(config) => (config.db_type.clone(), config.url.clone()),
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut api_env = EnvFile::new(env::EnvFileType::Yaml, db_type, db_url);
|
let mut api_env = EnvFile::new(env::EnvFileType::Yaml);
|
||||||
|
api_env.write_line("DATABASE__TYPE", db_type.to_string().as_str());
|
||||||
|
api_env.write_line("DATABASE__URL", db_url.as_str());
|
||||||
|
|
||||||
let mut db_env = api_env.clone();
|
let mut db_env = api_env.clone();
|
||||||
db_env.file_type = env::EnvFileType::DotEnv;
|
db_env.file_type = env::EnvFileType::DotEnv;
|
||||||
|
|
||||||
|
// agent related env vars
|
||||||
|
if let Some(agent) = agent_config
|
||||||
|
&& let ConfigInfoType::Containerized(agent) = agent
|
||||||
|
{
|
||||||
|
api_env.write_line(
|
||||||
|
"AGENT__SOCK__PATH",
|
||||||
|
format!("{}/{}", &agent.config.agent_config.sock_folder, SOCK_NAME).as_str(),
|
||||||
|
);
|
||||||
|
api_env.write_line(
|
||||||
|
"AGENT__NGINX__CONFIG__DIR",
|
||||||
|
&agent.config.agent_config.nginx_config_dir,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
let mut api_file =
|
let mut api_file =
|
||||||
std::fs::File::create(&api_config_path_absolute).expect("Failed to create API config file");
|
std::fs::File::create(&api_config_path_absolute).expect("Failed to create API config file");
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,9 @@
|
|||||||
@import "tailwindcss";
|
@import 'tailwindcss';
|
||||||
|
|
||||||
@theme {
|
@theme {
|
||||||
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif,
|
--font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
|
||||||
"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
html,
|
html,
|
||||||
body {
|
body {
|
||||||
@apply bg-white dark:bg-gray-950;
|
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
color-scheme: dark;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
46
apps/frontend/app/components/Form/Button.tsx
Normal file
46
apps/frontend/app/components/Form/Button.tsx
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { Button, type ButtonProps } from '@radix-ui/themes';
|
||||||
|
import { LoaderCircle } from 'lucide-react';
|
||||||
|
|
||||||
|
export type SubmitButtonProps = {
|
||||||
|
loading?: boolean;
|
||||||
|
label?:
|
||||||
|
| {
|
||||||
|
default?: string;
|
||||||
|
loading?: string;
|
||||||
|
}
|
||||||
|
| string;
|
||||||
|
} & React.ButtonHTMLAttributes<HTMLButtonElement> &
|
||||||
|
ButtonProps;
|
||||||
|
|
||||||
|
export function SubmitButton({ loading, label, ...props }: SubmitButtonProps) {
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
style={{
|
||||||
|
padding: '10px 14px',
|
||||||
|
borderRadius: 6,
|
||||||
|
border: 'none',
|
||||||
|
backgroundColor: 'var(--iris-9)',
|
||||||
|
}}
|
||||||
|
size="3"
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{loading
|
||||||
|
? typeof label === 'string'
|
||||||
|
? label
|
||||||
|
: label?.loading ?? <LoaderCircle className="animate-spin" style={{ width: 24, height: 24, marginRight: 4, verticalAlign: 'middle', color: 'white' }} />
|
||||||
|
: typeof label === 'string'
|
||||||
|
? label
|
||||||
|
: label?.default ?? 'Submit'}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ResetButton(props: React.ButtonHTMLAttributes<HTMLButtonElement>) {
|
||||||
|
return (
|
||||||
|
<button type="reset" {...props} style={{ padding: '10px 14px', borderRadius: 6, border: '1px solid var(--gray-5)', background: 'white', ...props.style }}>
|
||||||
|
{props.children ?? 'Reset'}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
103
apps/frontend/app/components/Form/TextField.tsx
Normal file
103
apps/frontend/app/components/Form/TextField.tsx
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
import type { AnyFieldMeta } from '@tanstack/react-form';
|
||||||
|
import { LucideEye, LucideEyeClosed } from 'lucide-react';
|
||||||
|
import { useCallback, useId, useState } from 'react';
|
||||||
|
import { InfoIcon, type InfoIconProps } from '../info';
|
||||||
|
import { Text } from '@radix-ui/themes';
|
||||||
|
|
||||||
|
export type TextFieldProps = {
|
||||||
|
label?: string;
|
||||||
|
value?: string;
|
||||||
|
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||||
|
labelProps?: React.LabelHTMLAttributes<HTMLLabelElement>;
|
||||||
|
labelDivProps?: React.HTMLAttributes<HTMLDivElement>;
|
||||||
|
infoIconProps?: InfoIconProps;
|
||||||
|
} & React.InputHTMLAttributes<HTMLInputElement> & {
|
||||||
|
type?: 'password';
|
||||||
|
showPasswordToggle?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function TextField({ label, value, onChange, labelProps, labelDivProps, showPasswordToggle, infoIconProps, ...rest }: TextFieldProps) {
|
||||||
|
const id = useId();
|
||||||
|
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||||
|
const handlePasswordVisibilitySet = useCallback(
|
||||||
|
(e: React.MouseEvent | React.TouchEvent, visible: boolean) => {
|
||||||
|
if (rest.type !== 'password') return;
|
||||||
|
e.preventDefault();
|
||||||
|
setIsPasswordVisible(() => visible);
|
||||||
|
},
|
||||||
|
[rest.type]
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<label htmlFor={id} style={{ display: 'block', marginBottom: 8 }} {...labelProps}>
|
||||||
|
{label && (
|
||||||
|
<div style={{ fontSize: 12, color: 'var(--gray-9)', marginBottom: 6, display: 'flex', alignItems: 'center' }} {...labelDivProps}>
|
||||||
|
{label}
|
||||||
|
{rest?.required && (
|
||||||
|
<Text size="3" style={{ color: 'var(--red-9)', marginLeft: 2 }}>
|
||||||
|
*
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{infoIconProps && <InfoIcon {...infoIconProps} style={{ marginLeft: 4, verticalAlign: 'middle' }} />}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||||
|
<input
|
||||||
|
{...rest}
|
||||||
|
type={rest.type === 'password' ? (isPasswordVisible && showPasswordToggle ? 'text' : 'password') : rest.type}
|
||||||
|
id={id}
|
||||||
|
value={value}
|
||||||
|
onChange={onChange}
|
||||||
|
style={{
|
||||||
|
width: '100%',
|
||||||
|
padding: '10px 12px',
|
||||||
|
borderRadius: 6,
|
||||||
|
border: '1px solid var(--gray-5)',
|
||||||
|
...rest?.style,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div
|
||||||
|
style={{ position: 'absolute', right: 12 }}
|
||||||
|
onMouseDown={(e) => {
|
||||||
|
handlePasswordVisibilitySet(e, true);
|
||||||
|
}}
|
||||||
|
onMouseUp={(e) => {
|
||||||
|
handlePasswordVisibilitySet(e, false);
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e) => {
|
||||||
|
handlePasswordVisibilitySet(e, false);
|
||||||
|
}}
|
||||||
|
onTouchStart={(e) => {
|
||||||
|
handlePasswordVisibilitySet(e, true);
|
||||||
|
}}
|
||||||
|
onTouchEnd={(e) => {
|
||||||
|
handlePasswordVisibilitySet(e, false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{showPasswordToggle ? isPasswordVisible ? <LucideEye size={16} /> : <LucideEyeClosed size={16} /> : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TextFieldErrorMessageProps = AnyFieldMeta & {
|
||||||
|
errorMessage?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function TextFieldErrorMessage({ isValid, errors, errorMessage }: TextFieldErrorMessageProps) {
|
||||||
|
return (
|
||||||
|
!isValid && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
marginTop: 4,
|
||||||
|
fontSize: 12,
|
||||||
|
color: 'var(--red-9)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{errorMessage ?? errors?.reduce((msg, err) => msg + err.message + ' ', '')}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
27
apps/frontend/app/components/home/TablePlaceholder.tsx
Normal file
27
apps/frontend/app/components/home/TablePlaceholder.tsx
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Flex, Text, Button, Separator, Box, Badge } from '@radix-ui/themes';
|
||||||
|
|
||||||
|
export default function TablePlaceholder() {
|
||||||
|
return (
|
||||||
|
<Flex direction="column" gap="3" p="4">
|
||||||
|
<Flex justify="between" align="center">
|
||||||
|
<Text weight="bold">Proxy Hosts</Text>
|
||||||
|
<Button size="1">Add Host</Button>
|
||||||
|
</Flex>
|
||||||
|
<Separator size="4" />
|
||||||
|
{[1, 2, 3].map((i) => (
|
||||||
|
<Flex key={i} justify="between" align="center">
|
||||||
|
<Box>
|
||||||
|
<Text size="2" weight="bold" as="div">
|
||||||
|
{`host-${i}.example.com`}
|
||||||
|
</Text>
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
{`http://10.0.0.${i}:8080`}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Badge color="green">Online</Badge>
|
||||||
|
</Flex>
|
||||||
|
))}
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
59
apps/frontend/app/components/info.tsx
Normal file
59
apps/frontend/app/components/info.tsx
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { Box } from '@radix-ui/themes';
|
||||||
|
import { Info, type LucideProps } from 'lucide-react';
|
||||||
|
import { Tooltip } from 'radix-ui';
|
||||||
|
import type { PropsWithChildren } from 'react';
|
||||||
|
|
||||||
|
export type InfoIconProps = PropsWithChildren<
|
||||||
|
{
|
||||||
|
tooltipContainerProps?: Omit<Tooltip.TooltipContentProps & React.RefAttributes<HTMLDivElement>, 'children'>;
|
||||||
|
} & Omit<LucideProps, 'ref'> &
|
||||||
|
React.RefAttributes<SVGSVGElement>
|
||||||
|
>;
|
||||||
|
|
||||||
|
export function InfoIcon({ tooltipContainerProps, children, ...iconProps }: InfoIconProps) {
|
||||||
|
return (
|
||||||
|
<Tooltip.Root>
|
||||||
|
<Tooltip.Trigger asChild>
|
||||||
|
<Info size={16} {...iconProps} />
|
||||||
|
</Tooltip.Trigger>
|
||||||
|
<Tooltip.Portal>
|
||||||
|
<Tooltip.Content
|
||||||
|
//
|
||||||
|
side="top"
|
||||||
|
align="center"
|
||||||
|
sideOffset={5}
|
||||||
|
alignOffset={0}
|
||||||
|
avoidCollisions={true}
|
||||||
|
style={{
|
||||||
|
color: 'black',
|
||||||
|
backgroundColor: 'white',
|
||||||
|
fontSize: 12,
|
||||||
|
boxShadow: '0 2px 10px rgba(0, 0, 0, 0.3)',
|
||||||
|
border: '1px solid var(--gray-5)',
|
||||||
|
}}
|
||||||
|
{...tooltipContainerProps}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<Tooltip.Arrow className="TooltipArrow" fill="white" />
|
||||||
|
</Tooltip.Content>
|
||||||
|
</Tooltip.Portal>
|
||||||
|
</Tooltip.Root>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TooltipContentContainer({ children, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
padding: '8px 12px',
|
||||||
|
color: 'black',
|
||||||
|
backgroundColor: 'white',
|
||||||
|
borderRadius: 4,
|
||||||
|
fontSize: 12,
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
89
apps/frontend/app/components/layout/SidebarContent.tsx
Normal file
89
apps/frontend/app/components/layout/SidebarContent.tsx
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import type React from 'react';
|
||||||
|
import { Box, Button, Flex, Heading, Separator, Text } from '@radix-ui/themes';
|
||||||
|
import type { NavItem } from './types';
|
||||||
|
import { Home, Globe, ArrowRight, Lock, Settings, User } from 'lucide-react';
|
||||||
|
import { useLayout } from '../../providers/LayoutProvider';
|
||||||
|
|
||||||
|
const navItems: { label: NavItem; icon: React.ReactNode }[] = [
|
||||||
|
{ label: 'Dashboard', icon: <Home size={16} /> },
|
||||||
|
{ label: 'Proxy Hosts', icon: <Globe size={16} /> },
|
||||||
|
{ label: 'Redirection', icon: <ArrowRight size={16} /> },
|
||||||
|
{ label: 'SSL', icon: <Lock size={16} /> },
|
||||||
|
{ label: 'Settings', icon: <Settings size={16} /> },
|
||||||
|
{ label: 'Profile', icon: <User size={16} /> },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export function SidebarContent() {
|
||||||
|
const { activeTab, setActiveTab, setIsMobileMenuOpen } = useLayout();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex direction="column" gap="2" p="4" style={{ height: '100%' }}>
|
||||||
|
<Flex align="center" gap="2" mb="6" px="2">
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
width: 32,
|
||||||
|
height: 32,
|
||||||
|
backgroundColor: 'var(--iris-9)',
|
||||||
|
borderRadius: 'var(--radius-2)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
color: 'white',
|
||||||
|
fontWeight: 'bold',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Y
|
||||||
|
</Box>
|
||||||
|
<Heading size="4" weight="bold">
|
||||||
|
YANPM
|
||||||
|
</Heading>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Flex direction="column" gap="1">
|
||||||
|
{navItems.map((item) => (
|
||||||
|
<Button
|
||||||
|
key={item.label}
|
||||||
|
variant={activeTab === item.label ? 'soft' : 'ghost'}
|
||||||
|
color={activeTab === item.label ? 'iris' : 'gray'}
|
||||||
|
onClick={() => {
|
||||||
|
setActiveTab(item.label);
|
||||||
|
setIsMobileMenuOpen(false);
|
||||||
|
}}
|
||||||
|
style={{ cursor: 'pointer', width: '100%', justifyContent: 'flex-start' }}
|
||||||
|
>
|
||||||
|
<Flex align="center" gap="3">
|
||||||
|
{item.icon}
|
||||||
|
<Text size="2" weight={activeTab === item.label ? 'bold' : 'medium'}>
|
||||||
|
{item.label}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Box style={{ marginTop: 'auto' }} pt="4">
|
||||||
|
<Separator size="4" mb="4" />
|
||||||
|
<Flex align="center" gap="3" px="2">
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
width: 32,
|
||||||
|
height: 32,
|
||||||
|
backgroundColor: 'var(--gray-5)',
|
||||||
|
borderRadius: '50%',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Box>
|
||||||
|
<Text size="1" weight="bold" as="div">
|
||||||
|
Admin User
|
||||||
|
</Text>
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
admin@example.com
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SidebarContent;
|
||||||
1
apps/frontend/app/components/layout/types.ts
Normal file
1
apps/frontend/app/components/layout/types.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export type NavItem = 'Dashboard' | 'Proxy Hosts' | 'Redirection' | 'SSL' | 'Settings' | 'Profile';
|
||||||
16
apps/frontend/app/components/theme.tsx
Normal file
16
apps/frontend/app/components/theme.tsx
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import type React from 'react';
|
||||||
|
import { Theme } from '@radix-ui/themes';
|
||||||
|
|
||||||
|
export type AppThemeProps = {
|
||||||
|
children: React.ReactNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function AppTheme({ children }: AppThemeProps) {
|
||||||
|
return (
|
||||||
|
<Theme accentColor="iris" grayColor="slate" panelBackground="translucent" radius="large">
|
||||||
|
{children}
|
||||||
|
</Theme>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AppTheme;
|
||||||
1
apps/frontend/app/empty-toastify.css
Normal file
1
apps/frontend/app/empty-toastify.css
Normal file
@@ -0,0 +1 @@
|
|||||||
|
/* intentionally empty: used to stub react-toastify CSS in production builds */
|
||||||
@@ -9,6 +9,7 @@ export namespace Schemas {
|
|||||||
version: string;
|
version: string;
|
||||||
};
|
};
|
||||||
export type LoginRequest = { password: string; username: string };
|
export type LoginRequest = { password: string; username: string };
|
||||||
|
export type UserInfo = { id: string; username: string };
|
||||||
|
|
||||||
// </Schemas>
|
// </Schemas>
|
||||||
}
|
}
|
||||||
@@ -41,6 +42,13 @@ export namespace Endpoints {
|
|||||||
parameters: never;
|
parameters: never;
|
||||||
responses: { 200: Schemas.HealthInfo; 404: unknown };
|
responses: { 200: Schemas.HealthInfo; 404: unknown };
|
||||||
};
|
};
|
||||||
|
export type get_Get_user_info = {
|
||||||
|
method: "GET";
|
||||||
|
path: "/api/user/me";
|
||||||
|
requestFormat: "json";
|
||||||
|
parameters: never;
|
||||||
|
responses: { 200: Schemas.UserInfo; 401: unknown; 500: unknown };
|
||||||
|
};
|
||||||
|
|
||||||
// </Endpoints>
|
// </Endpoints>
|
||||||
}
|
}
|
||||||
@@ -53,6 +61,7 @@ export type EndpointByMethod = {
|
|||||||
};
|
};
|
||||||
get: {
|
get: {
|
||||||
"/api/health/info": Endpoints.get_Get_health_info;
|
"/api/health/info": Endpoints.get_Get_health_info;
|
||||||
|
"/api/user/me": Endpoints.get_Get_user_info;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
73
apps/frontend/app/hooks/ResponseHelper.tsx
Normal file
73
apps/frontend/app/hooks/ResponseHelper.tsx
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import { AxiosError } from 'axios';
|
||||||
|
import { useLocation, useNavigate } from 'react-router';
|
||||||
|
import { SearchParamKeys } from '../lib/constants';
|
||||||
|
import { useQueryMessage } from './useQueryMessage';
|
||||||
|
import { QueryMessageCode, QueryMessageType } from '../lib/QueryMessages';
|
||||||
|
import { useCallback } from 'react';
|
||||||
|
import { displayForbiddenErrorToast, displayNetworkErrorToast, displayUnexpectedErrorToast } from '../lib/toasts';
|
||||||
|
|
||||||
|
export enum ResponseErrorToastId {
|
||||||
|
NetworkError = 'network-error',
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DefaultResponseErrorHandlerOptions = {
|
||||||
|
disableUnauthorizedHandling?: boolean;
|
||||||
|
disableHandleUnexpectedErrors?: boolean;
|
||||||
|
disableIgnoreCanceledRequests?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param err error value
|
||||||
|
* @returns {boolean} true if the error was handled, false otherwise
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function useResponseErrorHandler(): {
|
||||||
|
defaultResponseErrorHandler: typeof defaultResponseErrorHandler;
|
||||||
|
} {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const location = useLocation();
|
||||||
|
const { toSearchParamQueryMessage } = useQueryMessage();
|
||||||
|
|
||||||
|
const defaultResponseErrorHandler = useCallback(
|
||||||
|
(err: unknown, options?: DefaultResponseErrorHandlerOptions): boolean => {
|
||||||
|
if (!(err instanceof AxiosError) && !options?.disableHandleUnexpectedErrors) {
|
||||||
|
displayUnexpectedErrorToast();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(err instanceof AxiosError)) return false;
|
||||||
|
|
||||||
|
if (err.message === 'canceled') {
|
||||||
|
// request was aborted, ignore but return true to indicate it was handled
|
||||||
|
return !options?.disableIgnoreCanceledRequests;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err.message === 'Network Error') {
|
||||||
|
displayNetworkErrorToast();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle 401 Unauthorized globally
|
||||||
|
if (err.status === 401 && !options?.disableUnauthorizedHandling) {
|
||||||
|
// store current path for redirect after login
|
||||||
|
const currentPath = location.pathname + location.search;
|
||||||
|
const searchParam = new URLSearchParams();
|
||||||
|
searchParam.set(SearchParamKeys.Redirect, currentPath);
|
||||||
|
searchParam.set(SearchParamKeys.Message, toSearchParamQueryMessage(QueryMessageCode.SessionExpired, QueryMessageType.Info));
|
||||||
|
navigate(`/login?${searchParam.toString()}`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err.status === 403) {
|
||||||
|
displayForbiddenErrorToast();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
[location, navigate, toSearchParamQueryMessage]
|
||||||
|
);
|
||||||
|
|
||||||
|
return { defaultResponseErrorHandler };
|
||||||
|
}
|
||||||
48
apps/frontend/app/hooks/ensureLoggedIn.tsx
Normal file
48
apps/frontend/app/hooks/ensureLoggedIn.tsx
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
import { useNavigate } from 'react-router';
|
||||||
|
import { useAuth } from '../providers/AuthProvider';
|
||||||
|
import { useApi } from '../providers/ApiProvider';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useResponseErrorHandler } from './ResponseHelper';
|
||||||
|
|
||||||
|
export type EnsureLoggedInResult = {
|
||||||
|
checking: boolean;
|
||||||
|
loggedIn: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useEnsureLoggedIn(): EnsureLoggedInResult {
|
||||||
|
const { user, setUser } = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { tanstackApiClient } = useApi();
|
||||||
|
const { defaultResponseErrorHandler } = useResponseErrorHandler();
|
||||||
|
|
||||||
|
const { queryOptions: currentUserQuery } = tanstackApiClient.get('/api/user/me');
|
||||||
|
const { isFetched, isPending } = useQuery({
|
||||||
|
...currentUserQuery,
|
||||||
|
queryFn: async (...args) => {
|
||||||
|
try {
|
||||||
|
const data = await currentUserQuery.queryFn!(...args);
|
||||||
|
setUser({
|
||||||
|
id: data.id,
|
||||||
|
name: data.username,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
} catch (error) {
|
||||||
|
if (defaultResponseErrorHandler(error)) return {} as never;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user) {
|
||||||
|
navigate('/', { replace: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}, [user, setUser, navigate]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
checking: isPending,
|
||||||
|
loggedIn: isFetched && !!user,
|
||||||
|
};
|
||||||
|
}
|
||||||
111
apps/frontend/app/hooks/useQueryMessage.tsx
Normal file
111
apps/frontend/app/hooks/useQueryMessage.tsx
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { useCallback, useEffect, useRef, type ReactNode } from 'react';
|
||||||
|
import { useLocation, useSearchParams } from 'react-router';
|
||||||
|
import { toast } from 'react-toastify/unstyled';
|
||||||
|
import { SearchParamKeys } from '../lib/constants';
|
||||||
|
import { CODE_TO_MESSAGE_MAP, QueryMessageCode, QueryMessageType } from '../lib/QueryMessages';
|
||||||
|
|
||||||
|
type QueryMessageString = `${QueryMessageCode}__${QueryMessageType}`;
|
||||||
|
|
||||||
|
export type QueryMessage = {
|
||||||
|
type: QueryMessageType;
|
||||||
|
code: QueryMessageCode;
|
||||||
|
message: ReactNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UseQueryMessageOptions = {
|
||||||
|
displayMessages?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UseQueryMessageReturn = {
|
||||||
|
setQueryMessage: (messageCode: QueryMessageCode, messageType: QueryMessageType) => void;
|
||||||
|
clearQueryMessage: () => void;
|
||||||
|
toSearchParamQueryMessage: (message: QueryMessageCode, type: QueryMessageType) => QueryMessageString;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useQueryMessage(
|
||||||
|
{ displayMessages }: UseQueryMessageOptions = {
|
||||||
|
displayMessages: true,
|
||||||
|
}
|
||||||
|
): UseQueryMessageReturn {
|
||||||
|
const location = useLocation();
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
|
const messageStr = useRef<QueryMessageString | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Reset messageStr when location changes to allow re-displaying the same message on navigation
|
||||||
|
messageStr.current = null;
|
||||||
|
}, [location.pathname]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const queryMessageStr = searchParams.get(SearchParamKeys.Message);
|
||||||
|
if (!(queryMessageStr && queryMessageStr !== messageStr.current)) return;
|
||||||
|
const [queryMessage, queryMessageString] = toQueryMessage(queryMessageStr) ?? [null, null];
|
||||||
|
if (!queryMessage) return;
|
||||||
|
|
||||||
|
messageStr.current = queryMessageString;
|
||||||
|
if (displayMessages) {
|
||||||
|
toast[queryMessage.type](queryMessage.message, {
|
||||||
|
position: 'top-center',
|
||||||
|
autoClose: 5000,
|
||||||
|
hideProgressBar: false,
|
||||||
|
closeOnClick: true,
|
||||||
|
pauseOnHover: true,
|
||||||
|
draggable: false,
|
||||||
|
progress: undefined,
|
||||||
|
theme: 'colored',
|
||||||
|
toastId: 'login-route-info-message',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [displayMessages, searchParams]);
|
||||||
|
|
||||||
|
const setQueryMessage = useCallback(
|
||||||
|
(messageCode: QueryMessageCode, messageType: QueryMessageType) => {
|
||||||
|
const queryMessageString: QueryMessageString = `${messageCode}__${messageType}`;
|
||||||
|
messageStr.current = queryMessageString;
|
||||||
|
setSearchParams((prev) => {
|
||||||
|
prev.set(SearchParamKeys.Message, queryMessageString);
|
||||||
|
return prev;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[setSearchParams]
|
||||||
|
);
|
||||||
|
|
||||||
|
const clearQueryMessage = useCallback(() => {
|
||||||
|
messageStr.current = null;
|
||||||
|
setSearchParams((prev) => {
|
||||||
|
prev.delete(SearchParamKeys.Message);
|
||||||
|
return prev;
|
||||||
|
});
|
||||||
|
}, [setSearchParams]);
|
||||||
|
|
||||||
|
const toSearchParamQueryMessage = useCallback((message: QueryMessageCode, type: QueryMessageType): QueryMessageString => {
|
||||||
|
return `${message}__${type}`;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
setQueryMessage,
|
||||||
|
clearQueryMessage,
|
||||||
|
toSearchParamQueryMessage,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidQueryMessageCode(code: string): code is QueryMessageCode {
|
||||||
|
return Object.values(QueryMessageCode).includes(code as QueryMessageCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidQueryMessageType(type: string): type is QueryMessageType {
|
||||||
|
return Object.values(QueryMessageType).includes(type as QueryMessageType);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toQueryMessage(value: string): [QueryMessage, QueryMessageString] | null {
|
||||||
|
const [code, type] = value.split('__');
|
||||||
|
if (!isValidQueryMessageCode(code) || !isValidQueryMessageType(type)) return null;
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
code: code,
|
||||||
|
type: type,
|
||||||
|
message: CODE_TO_MESSAGE_MAP[code],
|
||||||
|
},
|
||||||
|
`${code}__${type}`,
|
||||||
|
];
|
||||||
|
}
|
||||||
20
apps/frontend/app/lib/QueryMessages.tsx
Normal file
20
apps/frontend/app/lib/QueryMessages.tsx
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
|
||||||
|
export enum QueryMessageType {
|
||||||
|
Info = 'info',
|
||||||
|
Success = 'success',
|
||||||
|
Warning = 'warning',
|
||||||
|
Error = 'error',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum QueryMessageCode {
|
||||||
|
SessionExpired = 'SESSION_EXPIRED',
|
||||||
|
InitializationRequired = 'INITIALIZATION_REQUIRED',
|
||||||
|
InitializationSuccessful = 'INITIALIZATION_SUCCESSFUL',
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CODE_TO_MESSAGE_MAP: Record<QueryMessageCode, ReactNode> = {
|
||||||
|
[QueryMessageCode.SessionExpired]: 'Your session has expired. Please log in again.',
|
||||||
|
[QueryMessageCode.InitializationRequired]: 'The application requires initialization. Please follow the setup instructions.',
|
||||||
|
[QueryMessageCode.InitializationSuccessful]: 'Initialization successful. Please log in.',
|
||||||
|
} as const;
|
||||||
@@ -65,7 +65,34 @@ function axiosResponseToFetchResponse(response: AxiosResponse): Response {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Response(response.data, {
|
// Normalize Axios response.data to a Fetch-compatible BodyInit
|
||||||
|
let body: BodyInit | null = null;
|
||||||
|
const data = response.data;
|
||||||
|
|
||||||
|
if (data == null) {
|
||||||
|
body = null;
|
||||||
|
} else if (
|
||||||
|
typeof data === 'string' ||
|
||||||
|
data instanceof Blob ||
|
||||||
|
data instanceof ArrayBuffer ||
|
||||||
|
ArrayBuffer.isView(data) ||
|
||||||
|
data instanceof FormData ||
|
||||||
|
data instanceof URLSearchParams
|
||||||
|
) {
|
||||||
|
body = data as BodyInit;
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
body = JSON.stringify(data);
|
||||||
|
if (!headers.has('content-type')) {
|
||||||
|
headers.set('content-type', 'application/json;charset=utf-8');
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
console.warn('Failed to stringify response data as JSON, falling back to string conversion.');
|
||||||
|
body = String(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response(body, {
|
||||||
status: response.status,
|
status: response.status,
|
||||||
statusText: response.statusText,
|
statusText: response.statusText,
|
||||||
headers: headers,
|
headers: headers,
|
||||||
|
|||||||
4
apps/frontend/app/lib/constants.ts
Normal file
4
apps/frontend/app/lib/constants.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export enum SearchParamKeys {
|
||||||
|
Redirect = 'redirect',
|
||||||
|
Message = 'message',
|
||||||
|
}
|
||||||
64
apps/frontend/app/lib/toasts.tsx
Normal file
64
apps/frontend/app/lib/toasts.tsx
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import { toast, type ToastOptions } from 'react-toastify/unstyled';
|
||||||
|
import { Text } from '@radix-ui/themes';
|
||||||
|
import { ResponseErrorToastId } from '../hooks/ResponseHelper';
|
||||||
|
|
||||||
|
export const displayUnexpectedErrorToast = (options: ToastOptions = {}) => {
|
||||||
|
toast.error(
|
||||||
|
<div>
|
||||||
|
<Text weight="bold">Unexpected Error:</Text>
|
||||||
|
<br /> An unexpected error occurred. Please try again later.
|
||||||
|
</div>,
|
||||||
|
{
|
||||||
|
position: 'top-center',
|
||||||
|
autoClose: false,
|
||||||
|
hideProgressBar: false,
|
||||||
|
closeOnClick: true,
|
||||||
|
pauseOnHover: true,
|
||||||
|
draggable: false,
|
||||||
|
progress: undefined,
|
||||||
|
theme: 'colored',
|
||||||
|
...options,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const displayNetworkErrorToast = (options: ToastOptions = {}) => {
|
||||||
|
toast.error(
|
||||||
|
<div>
|
||||||
|
<Text weight="bold">Network Error:</Text>
|
||||||
|
<br /> Unable to reach the server. Please check your internet connection and try again.
|
||||||
|
</div>,
|
||||||
|
{
|
||||||
|
toastId: ResponseErrorToastId.NetworkError,
|
||||||
|
position: 'top-center',
|
||||||
|
autoClose: false,
|
||||||
|
hideProgressBar: false,
|
||||||
|
closeOnClick: true,
|
||||||
|
pauseOnHover: true,
|
||||||
|
draggable: false,
|
||||||
|
progress: undefined,
|
||||||
|
theme: 'colored',
|
||||||
|
...options,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const displayForbiddenErrorToast = (options: ToastOptions = {}) => {
|
||||||
|
toast.error(
|
||||||
|
<div>
|
||||||
|
<Text weight="bold">Forbidden:</Text>
|
||||||
|
<br /> You do not have permission to perform this action.
|
||||||
|
</div>,
|
||||||
|
{
|
||||||
|
position: 'top-center',
|
||||||
|
autoClose: 5000,
|
||||||
|
hideProgressBar: false,
|
||||||
|
closeOnClick: true,
|
||||||
|
pauseOnHover: true,
|
||||||
|
draggable: false,
|
||||||
|
progress: undefined,
|
||||||
|
theme: 'colored',
|
||||||
|
...options,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
56
apps/frontend/app/providers/ApiHealthProvider.tsx
Normal file
56
apps/frontend/app/providers/ApiHealthProvider.tsx
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import { useNavigate } from 'react-router';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { createContext, use, type PropsWithChildren } from 'react';
|
||||||
|
import { useApi } from './ApiProvider';
|
||||||
|
import { useResponseErrorHandler } from '../hooks/ResponseHelper';
|
||||||
|
import type { Schemas } from '../generated/api-client/api-client';
|
||||||
|
|
||||||
|
export type HealthStatus = Schemas.HealthInfo;
|
||||||
|
|
||||||
|
export type ApiHealthProviderProps = PropsWithChildren<object>;
|
||||||
|
export type ApiHealthContextType = {
|
||||||
|
healthStatus: HealthStatus | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ApiHealthContext = createContext<ApiHealthContextType | null>(null);
|
||||||
|
|
||||||
|
export const ApiHealthProvider: React.FC<ApiHealthProviderProps> = ({ children }) => {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { tanstackApiClient } = useApi();
|
||||||
|
const { defaultResponseErrorHandler } = useResponseErrorHandler();
|
||||||
|
|
||||||
|
const { queryOptions: healthInfoQuery } = tanstackApiClient.get('/api/health/info');
|
||||||
|
const { data } = useQuery({
|
||||||
|
...healthInfoQuery,
|
||||||
|
queryFn: async (...args) => {
|
||||||
|
try {
|
||||||
|
const data = await healthInfoQuery.queryFn!(...args);
|
||||||
|
if (!data.is_initialized) {
|
||||||
|
navigate('/init');
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
} catch (error) {
|
||||||
|
if (defaultResponseErrorHandler(error)) return {} as never;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ApiHealthContext
|
||||||
|
value={{
|
||||||
|
healthStatus: data,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</ApiHealthContext>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useApiHealth = (): ApiHealthContextType => {
|
||||||
|
const context = use(ApiHealthContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useApiHealth must be used within an ApiHealthProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
};
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { createContext, use, useContext, type PropsWithChildren } from 'react';
|
import { createContext, use, type PropsWithChildren } from 'react';
|
||||||
import { createTanstackApi, createApi } from '../lib/api';
|
import { createTanstackApi, createApi } from '../lib/api';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||||
|
|
||||||
type ApiProviderProps = PropsWithChildren<{}>;
|
type ApiProviderProps = PropsWithChildren<object>;
|
||||||
type ApiContextType = {
|
type ApiContextType = {
|
||||||
apiClient: ReturnType<typeof createApi>;
|
apiClient: ReturnType<typeof createApi>;
|
||||||
tanstackApiClient: ReturnType<typeof createTanstackApi>;
|
tanstackApiClient: ReturnType<typeof createTanstackApi>;
|
||||||
@@ -34,8 +34,14 @@ export const ApiProvider: React.FC<ApiProviderProps> = ({ children }) => {
|
|||||||
const axiosInstance = axios.create({
|
const axiosInstance = axios.create({
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const internalAxiosInstance = axios.create({
|
||||||
|
withCredentials: true,
|
||||||
|
});
|
||||||
|
|
||||||
const apiClient = createApi(axiosInstance);
|
const apiClient = createApi(axiosInstance);
|
||||||
const tanstackApiClient = createTanstackApi(axiosInstance);
|
const tanstackApiClient = createTanstackApi(internalAxiosInstance);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<ApiContext
|
<ApiContext
|
||||||
|
|||||||
47
apps/frontend/app/providers/AuthProvider.tsx
Normal file
47
apps/frontend/app/providers/AuthProvider.tsx
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { createContext, use, useCallback, useState, type PropsWithChildren } from 'react';
|
||||||
|
|
||||||
|
export type User = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AuthProviderProps = PropsWithChildren<object>;
|
||||||
|
export type AuthContextType = {
|
||||||
|
setUser: (user: User) => void;
|
||||||
|
logOut: () => void;
|
||||||
|
user: User | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const AuthContext = createContext<AuthContextType | null>(null);
|
||||||
|
|
||||||
|
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
|
||||||
|
const [user, setUserState] = useState<User | null>(null);
|
||||||
|
|
||||||
|
const setUser = useCallback((user: User) => {
|
||||||
|
setUserState(user);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const logout = useCallback(() => {
|
||||||
|
setUserState(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthContext
|
||||||
|
value={{
|
||||||
|
user: user,
|
||||||
|
logOut: logout,
|
||||||
|
setUser: setUser,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</AuthContext>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useAuth() {
|
||||||
|
const context = use(AuthContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useAuth must be used within a AuthProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
18
apps/frontend/app/providers/FormProvider.tsx
Normal file
18
apps/frontend/app/providers/FormProvider.tsx
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { createFormHook, createFormHookContexts } from '@tanstack/react-form';
|
||||||
|
import { TextField, TextFieldErrorMessage } from '../components/Form/TextField';
|
||||||
|
import { ResetButton, SubmitButton } from '../components/Form/Button';
|
||||||
|
|
||||||
|
const { fieldContext, formContext } = createFormHookContexts();
|
||||||
|
|
||||||
|
export const formHook = createFormHook({
|
||||||
|
fieldComponents: {
|
||||||
|
TextField,
|
||||||
|
TextFieldErrorMessage,
|
||||||
|
},
|
||||||
|
formComponents: {
|
||||||
|
SubmitButton,
|
||||||
|
ResetButton,
|
||||||
|
},
|
||||||
|
fieldContext,
|
||||||
|
formContext,
|
||||||
|
});
|
||||||
38
apps/frontend/app/providers/LayoutProvider.tsx
Normal file
38
apps/frontend/app/providers/LayoutProvider.tsx
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { createContext, use, useState, type PropsWithChildren } from 'react';
|
||||||
|
import type { NavItem } from '../components/layout/types';
|
||||||
|
|
||||||
|
type LayoutProviderProps = PropsWithChildren<object>;
|
||||||
|
type LayoutContextType = {
|
||||||
|
activeTab: NavItem;
|
||||||
|
setActiveTab: (tab: NavItem) => void;
|
||||||
|
isMobileMenuOpen: boolean;
|
||||||
|
setIsMobileMenuOpen: (open: boolean) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const LayoutContext = createContext<LayoutContextType | null>(null);
|
||||||
|
|
||||||
|
export const LayoutProvider: React.FC<LayoutProviderProps> = ({ children }) => {
|
||||||
|
const [activeTab, setActiveTab] = useState<NavItem>('Dashboard');
|
||||||
|
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<LayoutContext
|
||||||
|
value={{
|
||||||
|
activeTab,
|
||||||
|
setActiveTab,
|
||||||
|
isMobileMenuOpen,
|
||||||
|
setIsMobileMenuOpen,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</LayoutContext>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useLayout() {
|
||||||
|
const context = use(LayoutContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useLayout must be used within a LayoutProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
@@ -1,8 +1,18 @@
|
|||||||
import { isRouteErrorResponse, Links, Meta, Outlet, Scripts, ScrollRestoration } from 'react-router';
|
import { isRouteErrorResponse, Links, Meta, Outlet, Scripts, ScrollRestoration } from 'react-router';
|
||||||
import type { Route } from './+types/root';
|
import type { Route } from './+types/root';
|
||||||
|
import '@radix-ui/themes/styles.css';
|
||||||
import './app.css';
|
import './app.css';
|
||||||
import { Theme } from '@radix-ui/themes';
|
// start: react-toastify special import
|
||||||
|
// ! MUST use unstyled version for dev server build, styled version for production build is handled in vite.config.ts
|
||||||
|
import { ToastContainer } from 'react-toastify/unstyled';
|
||||||
|
import 'react-toastify/ReactToastify.css';
|
||||||
|
// end: react-toastify special import
|
||||||
|
import AppTheme from './components/theme';
|
||||||
import { ApiProvider } from './providers/ApiProvider';
|
import { ApiProvider } from './providers/ApiProvider';
|
||||||
|
import { LayoutProvider } from './providers/LayoutProvider';
|
||||||
|
import { Tooltip } from 'radix-ui';
|
||||||
|
import { AuthProvider } from './providers/AuthProvider';
|
||||||
|
import { ApiHealthProvider } from './providers/ApiHealthProvider';
|
||||||
|
|
||||||
export const links: Route.LinksFunction = () => [];
|
export const links: Route.LinksFunction = () => [];
|
||||||
|
|
||||||
@@ -26,11 +36,23 @@ export function Layout({ children }: { children: React.ReactNode }) {
|
|||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<Theme>
|
<>
|
||||||
<ApiProvider>
|
<AppTheme>
|
||||||
<Outlet />
|
<ApiProvider>
|
||||||
</ApiProvider>
|
<Tooltip.Provider delayDuration={250}>
|
||||||
</Theme>
|
<LayoutProvider>
|
||||||
|
<ApiHealthProvider>
|
||||||
|
<AuthProvider>
|
||||||
|
<Outlet />
|
||||||
|
</AuthProvider>
|
||||||
|
</ApiHealthProvider>
|
||||||
|
</LayoutProvider>
|
||||||
|
</Tooltip.Provider>
|
||||||
|
</ApiProvider>
|
||||||
|
</AppTheme>
|
||||||
|
|
||||||
|
<ToastContainer />
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { type RouteConfig, index, route } from '@react-router/dev/routes';
|
import { type RouteConfig, index, layout, route } from '@react-router/dev/routes';
|
||||||
|
|
||||||
export default [
|
export default [
|
||||||
index('routes/home.tsx'),
|
route('login', 'routes/auth/login.tsx'),
|
||||||
|
route('init', 'routes/init.tsx'),
|
||||||
|
layout('routes/layout.tsx', [index('routes/home.tsx')]),
|
||||||
// catch-all 404 route
|
// catch-all 404 route
|
||||||
route('*', 'routes/404.tsx'),
|
route('*', 'routes/404.tsx'),
|
||||||
] satisfies RouteConfig;
|
] satisfies RouteConfig;
|
||||||
|
|||||||
153
apps/frontend/app/routes/auth/login.tsx
Normal file
153
apps/frontend/app/routes/auth/login.tsx
Normal file
@@ -0,0 +1,153 @@
|
|||||||
|
import { Box, Container, Flex, Heading } from '@radix-ui/themes';
|
||||||
|
import { useMutation } from '@tanstack/react-query';
|
||||||
|
import { useLocation, useNavigate } from 'react-router';
|
||||||
|
import { toast } from 'react-toastify/unstyled';
|
||||||
|
import * as v from 'valibot';
|
||||||
|
import { useResponseErrorHandler } from '../../hooks/ResponseHelper';
|
||||||
|
import { useApi } from '../../providers/ApiProvider';
|
||||||
|
import { formHook } from '../../providers/FormProvider';
|
||||||
|
import type { Route } from './+types/login';
|
||||||
|
import { SearchParamKeys } from '../../lib/constants';
|
||||||
|
import { AxiosError } from 'axios';
|
||||||
|
import { useQueryMessage } from '../../hooks/useQueryMessage';
|
||||||
|
|
||||||
|
const loginFormSchema = v.object({
|
||||||
|
username: v.pipe(v.string(), v.trim(), v.minLength(1, 'Username is required')),
|
||||||
|
password: v.pipe(v.string(), v.minLength(1, 'Password is required')),
|
||||||
|
});
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-empty-pattern
|
||||||
|
export function meta({}: Route.MetaArgs): Route.MetaDescriptors {
|
||||||
|
return [{ title: 'Login | YANPM' }];
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: remember me
|
||||||
|
export default function LoginRoute() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const location = useLocation();
|
||||||
|
const { tanstackApiClient } = useApi();
|
||||||
|
const { defaultResponseErrorHandler } = useResponseErrorHandler();
|
||||||
|
useQueryMessage();
|
||||||
|
|
||||||
|
const { mutateAsync: login, isPending } = useMutation({
|
||||||
|
...tanstackApiClient.mutation('post', '/api/auth/login').mutationOptions,
|
||||||
|
onSuccess: async () => {
|
||||||
|
const searchParams = new URLSearchParams(location.search);
|
||||||
|
const redirectTo = searchParams.get(SearchParamKeys.Redirect);
|
||||||
|
if (redirectTo) {
|
||||||
|
navigate(redirectTo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
navigate('/');
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
if (defaultResponseErrorHandler(error, { disableUnauthorizedHandling: true })) return;
|
||||||
|
if (error instanceof AxiosError && error.status === 401) {
|
||||||
|
toast.error('Invalid username or password.', {
|
||||||
|
position: 'top-center',
|
||||||
|
autoClose: 5000,
|
||||||
|
hideProgressBar: false,
|
||||||
|
closeOnClick: true,
|
||||||
|
pauseOnHover: true,
|
||||||
|
draggable: false,
|
||||||
|
progress: undefined,
|
||||||
|
theme: 'colored',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error('Login failed:', error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const form = formHook.useAppForm({
|
||||||
|
defaultValues: {
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
},
|
||||||
|
validators: {
|
||||||
|
onBlur: loginFormSchema,
|
||||||
|
onSubmit: loginFormSchema,
|
||||||
|
},
|
||||||
|
|
||||||
|
onSubmit: async ({ value }) => {
|
||||||
|
toast.dismiss();
|
||||||
|
return await login({ body: { password: value.password, username: value.username } }).catch(() => {});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Flex align="center" justify="center" style={{ minHeight: 'calc(100vh - 64px)' }}>
|
||||||
|
<Container size="3" p="0">
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
maxWidth: 420,
|
||||||
|
margin: '40px auto',
|
||||||
|
backgroundColor: 'white',
|
||||||
|
padding: 24,
|
||||||
|
borderRadius: 8,
|
||||||
|
boxShadow: '0 6px 18px rgba(15,23,42,0.2)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Heading size="6" style={{ marginBottom: 16, alignSelf: 'center' }}>
|
||||||
|
Sign In
|
||||||
|
</Heading>
|
||||||
|
<form
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
form.handleSubmit();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<form.AppField
|
||||||
|
name="username"
|
||||||
|
children={(field) => (
|
||||||
|
<>
|
||||||
|
<field.TextField
|
||||||
|
label={'Username'}
|
||||||
|
value={field.state.value}
|
||||||
|
autoComplete="username"
|
||||||
|
spellCheck={false}
|
||||||
|
required
|
||||||
|
onChange={(e) => field.handleChange(e.target.value)}
|
||||||
|
/>
|
||||||
|
<field.TextFieldErrorMessage {...field.state.meta} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<form.AppField
|
||||||
|
name="password"
|
||||||
|
children={(field) => (
|
||||||
|
<>
|
||||||
|
<field.TextField
|
||||||
|
label={'Password'}
|
||||||
|
value={field.state.value}
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
autoComplete="current-password"
|
||||||
|
onChange={(e) => field.handleChange(e.target.value)}
|
||||||
|
showPasswordToggle
|
||||||
|
/>
|
||||||
|
<field.TextFieldErrorMessage {...field.state.meta} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div style={{ marginTop: 18, display: 'flex', gap: 8, justifySelf: 'center' }}>
|
||||||
|
<form.SubmitButton
|
||||||
|
loading={isPending}
|
||||||
|
label={{
|
||||||
|
default: 'Sign In',
|
||||||
|
loading: 'Signing In…',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Box>
|
||||||
|
</Container>
|
||||||
|
</Flex>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,13 +1,75 @@
|
|||||||
import { Text } from '@radix-ui/themes';
|
import { Box, Button, Card, Flex, Grid, Heading, Text } from '@radix-ui/themes';
|
||||||
import type { Route } from './+types/home';
|
import type { Route } from './+types/home';
|
||||||
import { useContext } from 'react';
|
import TablePlaceholder from '../components/home/TablePlaceholder';
|
||||||
import { useApi } from '../providers/ApiProvider';
|
import { useLayout } from '../providers/LayoutProvider';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useEnsureLoggedIn } from '../hooks/ensureLoggedIn';
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-empty-pattern
|
||||||
export function meta({}: Route.MetaArgs) {
|
export function meta({}: Route.MetaArgs) {
|
||||||
return [{ title: 'YANPM' }, { name: 'description', content: 'Welcome to Yet Another Nginx Proxy Manager!' }];
|
return [{ title: 'Proxy Host Demo | YANPM' }, { name: 'description', content: 'Demo of the unified navigation paradigm.' }];
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Home() {
|
export default function ProxyHostDemo() {
|
||||||
return <Text>Welcome to Yet Another Nginx Proxy Manager!</Text>;
|
useEnsureLoggedIn();
|
||||||
|
const { activeTab } = useLayout();
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<Heading size="7" mb="1">
|
||||||
|
{activeTab}
|
||||||
|
</Heading>
|
||||||
|
<Text color="gray" mb="4" as="p">
|
||||||
|
This is the {activeTab.toLowerCase()} page demo.
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
<Grid columns={{ initial: '1', sm: '2', lg: '3' }} gap="4">
|
||||||
|
<Card size="2">
|
||||||
|
<Flex direction="column" gap="2">
|
||||||
|
<Text size="2" weight="bold">
|
||||||
|
Status Overview
|
||||||
|
</Text>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
Everything is running smoothly in your {activeTab.toLowerCase()} section.
|
||||||
|
</Text>
|
||||||
|
<Button variant="surface" size="1" style={{ width: 'fit-content' }} mt="1">
|
||||||
|
View Details
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
<Card size="2">
|
||||||
|
<Flex direction="column" gap="2">
|
||||||
|
<Text size="2" weight="bold">
|
||||||
|
Recent Activity
|
||||||
|
</Text>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
No recent changes detected in the last 24 hours.
|
||||||
|
</Text>
|
||||||
|
<Button variant="surface" size="1" style={{ width: 'fit-content' }} mt="1">
|
||||||
|
Refresh
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
<Card size="2">
|
||||||
|
<Flex direction="column" gap="2">
|
||||||
|
<Text size="2" weight="bold">
|
||||||
|
Quick Actions
|
||||||
|
</Text>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
Common tasks related to {activeTab.toLowerCase()} are available here.
|
||||||
|
</Text>
|
||||||
|
<Button variant="solid" size="1" style={{ width: 'fit-content' }} mt="1">
|
||||||
|
Get Started
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
</Grid>
|
||||||
|
|
||||||
|
{activeTab === 'Proxy Hosts' && (
|
||||||
|
<Box mt="6">
|
||||||
|
<Card variant="surface">
|
||||||
|
<TablePlaceholder />
|
||||||
|
</Card>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
161
apps/frontend/app/routes/init.tsx
Normal file
161
apps/frontend/app/routes/init.tsx
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
import { Box, Container, Flex, Heading, Text } from '@radix-ui/themes';
|
||||||
|
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||||
|
import { useNavigate } from 'react-router';
|
||||||
|
import { toast } from 'react-toastify/unstyled';
|
||||||
|
import * as v from 'valibot';
|
||||||
|
import { useResponseErrorHandler } from '../hooks/ResponseHelper';
|
||||||
|
import { useApi } from '../providers/ApiProvider';
|
||||||
|
import { formHook } from '../providers/FormProvider';
|
||||||
|
import { TooltipContentContainer } from '../components/info';
|
||||||
|
import { SearchParamKeys } from '../lib/constants';
|
||||||
|
import { useQueryMessage } from '../hooks/useQueryMessage';
|
||||||
|
import { QueryMessageCode, QueryMessageType } from '../lib/QueryMessages';
|
||||||
|
|
||||||
|
const initFormSchema = v.object({
|
||||||
|
username: v.pipe(v.string(), v.trim(), v.minLength(1, 'Username is required')),
|
||||||
|
password: v.pipe(v.string(), v.minLength(1, 'Password is required')),
|
||||||
|
setup_secret: v.pipe(v.string(), v.minLength(1, 'Setup secret is required')),
|
||||||
|
});
|
||||||
|
|
||||||
|
export default function InitRoute() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { tanstackApiClient } = useApi();
|
||||||
|
const { defaultResponseErrorHandler } = useResponseErrorHandler();
|
||||||
|
const { toSearchParamQueryMessage } = useQueryMessage();
|
||||||
|
|
||||||
|
const { mutateAsync: initAdmin, isPending } = useMutation({
|
||||||
|
...tanstackApiClient.mutation('post', '/api/auth/init_admin').mutationOptions,
|
||||||
|
onSuccess: async () => {
|
||||||
|
const searchParams = new URLSearchParams();
|
||||||
|
searchParams.set(SearchParamKeys.Message, toSearchParamQueryMessage(QueryMessageCode.InitializationSuccessful, QueryMessageType.Success));
|
||||||
|
navigate(`/login?${searchParams.toString()}`);
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
if (defaultResponseErrorHandler(error)) return;
|
||||||
|
console.error('Init failed:', error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { queryOptions: healthInfoQuery } = tanstackApiClient.get('/api/health/info');
|
||||||
|
useQuery({
|
||||||
|
...healthInfoQuery,
|
||||||
|
queryFn: async (...args) => {
|
||||||
|
try {
|
||||||
|
const data = await healthInfoQuery.queryFn!(...args);
|
||||||
|
if (data.is_initialized) {
|
||||||
|
navigate('/login', { replace: true });
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
} catch (error) {
|
||||||
|
if (defaultResponseErrorHandler(error)) return {} as never;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const form = formHook.useAppForm({
|
||||||
|
defaultValues: { username: '', password: '', setup_secret: '' },
|
||||||
|
validators: { onBlur: initFormSchema, onSubmit: initFormSchema },
|
||||||
|
onSubmit: async ({ value }) => {
|
||||||
|
toast.dismiss();
|
||||||
|
return await initAdmin({ body: { username: value.username, password: value.password, setup_secret: value.setup_secret } });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Flex align="center" justify="center" style={{ minHeight: 'calc(100vh - 64px)' }}>
|
||||||
|
<Container size="3" p="0">
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
maxWidth: 480,
|
||||||
|
margin: '40px auto',
|
||||||
|
backgroundColor: 'white',
|
||||||
|
padding: 24,
|
||||||
|
borderRadius: 8,
|
||||||
|
boxShadow: '0 6px 18px rgba(15,23,42,0.06)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Heading size="6" style={{ marginBottom: 12, alignSelf: 'center' }}>
|
||||||
|
Initialize YANPM
|
||||||
|
</Heading>
|
||||||
|
|
||||||
|
<Heading size="3" style={{ marginBottom: 24, color: 'var(--gray-11)', alignSelf: 'center' }}>
|
||||||
|
Create the initial admin user
|
||||||
|
</Heading>
|
||||||
|
<form
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
form.handleSubmit();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<form.AppField
|
||||||
|
name="username"
|
||||||
|
children={(field) => (
|
||||||
|
<>
|
||||||
|
<field.TextField
|
||||||
|
label="Username"
|
||||||
|
value={field.state.value}
|
||||||
|
autoComplete="username"
|
||||||
|
spellCheck={false}
|
||||||
|
required
|
||||||
|
onChange={(e) => field.handleChange(e.target.value)}
|
||||||
|
/>
|
||||||
|
<field.TextFieldErrorMessage {...field.state.meta} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<form.AppField
|
||||||
|
name="password"
|
||||||
|
children={(field) => (
|
||||||
|
<>
|
||||||
|
<field.TextField
|
||||||
|
label="Password"
|
||||||
|
value={field.state.value}
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
autoComplete="new-password"
|
||||||
|
onChange={(e) => field.handleChange(e.target.value)}
|
||||||
|
showPasswordToggle
|
||||||
|
/>
|
||||||
|
<field.TextFieldErrorMessage {...field.state.meta} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<form.AppField
|
||||||
|
name="setup_secret"
|
||||||
|
children={(field) => (
|
||||||
|
<>
|
||||||
|
<field.TextField
|
||||||
|
label="Setup Secret"
|
||||||
|
value={field.state.value}
|
||||||
|
required
|
||||||
|
onChange={(e) => field.handleChange(e.target.value)}
|
||||||
|
infoIconProps={{
|
||||||
|
children: (
|
||||||
|
<TooltipContentContainer>
|
||||||
|
<Text>This secret is provided when the API server is first started. Refer to your server logs to find it.</Text>
|
||||||
|
</TooltipContentContainer>
|
||||||
|
),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<field.TextFieldErrorMessage {...field.state.meta} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div style={{ marginTop: 18, display: 'flex', gap: 8, justifySelf: 'center' }}>
|
||||||
|
<form.SubmitButton loading={isPending} label={{ default: 'Initialize' }} />
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Box>
|
||||||
|
</Container>
|
||||||
|
</Flex>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
88
apps/frontend/app/routes/layout.tsx
Normal file
88
apps/frontend/app/routes/layout.tsx
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { Flex, Box, Container, Dialog, Heading, IconButton, TextField } from '@radix-ui/themes';
|
||||||
|
import SidebarContent from '../components/layout/SidebarContent';
|
||||||
|
import { useLayout } from '../providers/LayoutProvider';
|
||||||
|
import { Menu, Search, Bell } from 'lucide-react';
|
||||||
|
import { Outlet } from 'react-router';
|
||||||
|
|
||||||
|
export default function LayoutContainer() {
|
||||||
|
const { activeTab, isMobileMenuOpen, setIsMobileMenuOpen } = useLayout();
|
||||||
|
return (
|
||||||
|
<Flex style={{ minHeight: '100vh', backgroundColor: 'var(--gray-2)' }}>
|
||||||
|
{/* Desktop Sidebar */}
|
||||||
|
<Box
|
||||||
|
display={{ initial: 'none', md: 'block' }}
|
||||||
|
style={{
|
||||||
|
width: '260px',
|
||||||
|
backgroundColor: 'white',
|
||||||
|
borderRight: '1px solid var(--gray-4)',
|
||||||
|
position: 'sticky',
|
||||||
|
top: 0,
|
||||||
|
minHeight: '100vh',
|
||||||
|
overflowY: 'auto',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SidebarContent />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Main Content Area */}
|
||||||
|
<Box style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
{' '}
|
||||||
|
{/* Top Header (Mobile & Desktop) */}
|
||||||
|
<Flex
|
||||||
|
align="center"
|
||||||
|
justify="between"
|
||||||
|
px="4"
|
||||||
|
style={{
|
||||||
|
height: '64px',
|
||||||
|
backgroundColor: 'white',
|
||||||
|
borderBottom: '1px solid var(--gray-4)',
|
||||||
|
position: 'sticky',
|
||||||
|
top: 0,
|
||||||
|
zIndex: 10,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Flex align="center" gap="3">
|
||||||
|
<Box display={{ md: 'none' }}>
|
||||||
|
<Dialog.Root open={isMobileMenuOpen} onOpenChange={setIsMobileMenuOpen}>
|
||||||
|
<Dialog.Trigger>
|
||||||
|
<IconButton variant="ghost" color="gray">
|
||||||
|
<Menu />
|
||||||
|
</IconButton>
|
||||||
|
</Dialog.Trigger>
|
||||||
|
<Dialog.Content
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
left: 0,
|
||||||
|
top: 0,
|
||||||
|
bottom: 0,
|
||||||
|
margin: 0,
|
||||||
|
width: '280px',
|
||||||
|
borderRadius: 0,
|
||||||
|
padding: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SidebarContent />
|
||||||
|
</Dialog.Content>
|
||||||
|
</Dialog.Root>
|
||||||
|
</Box>
|
||||||
|
<Heading size="4">{activeTab}</Heading>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Flex align="center" gap="3">
|
||||||
|
<TextField.Root placeholder="Search..." size="2">
|
||||||
|
<TextField.Slot>
|
||||||
|
<Search />
|
||||||
|
</TextField.Slot>
|
||||||
|
</TextField.Root>
|
||||||
|
<IconButton variant="ghost" color="gray">
|
||||||
|
<Bell />
|
||||||
|
</IconButton>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
<Container size="4" p="5" style={{ paddingTop: 20 }}>
|
||||||
|
<Outlet />
|
||||||
|
</Container>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
5
apps/frontend/app/vite-env.d.ts
vendored
5
apps/frontend/app/vite-env.d.ts
vendored
@@ -1,7 +1,6 @@
|
|||||||
interface ViteTypeOptions {
|
interface ViteTypeOptions {
|
||||||
// By adding this line, you can make the type of ImportMetaEnv strict
|
// disallow unknown keys.
|
||||||
// to disallow unknown keys.
|
strictImportMetaEnv: unknown;
|
||||||
// strictImportMetaEnv: unknown
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ImportMetaEnv {
|
interface ImportMetaEnv {
|
||||||
|
|||||||
42
apps/frontend/eslint.config.ts
Normal file
42
apps/frontend/eslint.config.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import js from '@eslint/js';
|
||||||
|
import globals from 'globals';
|
||||||
|
import tseslint from 'typescript-eslint';
|
||||||
|
import pluginReact from 'eslint-plugin-react';
|
||||||
|
import pluginReactHooks from 'eslint-plugin-react-hooks';
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{
|
||||||
|
// Ignore files and directories
|
||||||
|
ignores: ['node_modules', 'app/generated', 'build', '.react-router'],
|
||||||
|
},
|
||||||
|
js.configs.recommended,
|
||||||
|
...tseslint.configs.recommended,
|
||||||
|
{
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
...globals.node,
|
||||||
|
},
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.json', './tsconfig.node.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
rules: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...pluginReact.configs.flat.recommended, // Enables core React rules
|
||||||
|
...pluginReactHooks.configs.flat.recommended, // Enables React Hooks rules
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
ecmaFeatures: {
|
||||||
|
jsx: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user