feat(admin): 接通后台预览与权限校验
continuous-integration/drone/push Build is failing Details

This commit is contained in:
dongjf 2026-11-29 19:35:12 +08:00
parent f67f683373
commit a1dff7064e
12 changed files with 500 additions and 7 deletions

View File

@ -9,5 +9,6 @@ RUN npm run build
FROM nginx:1.31-alpine
ENV ATLAS_GATEWAY_URL=http://gateway:8080
RUN mkdir -p /etc/nginx/admin-identity
COPY nginx.conf.template /etc/nginx/templates/default.conf.template
COPY --from=build /app/dist /usr/share/nginx/html

View File

@ -10,4 +10,6 @@ docker build -t item-atlas-admin:dev .
镜像监听 8080。容器环境变量 `ATLAS_GATEWAY_URL` 指向内网网关。`VITE_OIDC_URL`、`VITE_OIDC_REALM` 是构建参数,对应管理员登录所用的 Keycloak。应用只向同源 `/api/admin/` 发请求,由 Nginx 转发。Keycloak 的回调、权限和入口配置见 [身份和图片部署](../../docs/deployment/identity-and-media.md)。
本机预览使用同源 `/auth` 和独立 realm。部署、测试账号与排错步骤见 [管理后台本机预览](../../deploy/admin-preview/README.md)。登录过期或接口拒绝管理员权限时,页面会清空已读取的空间数据。
列表使用 `GET /api/admin/households?q=&limit=25&offset=0`,按名称及 ID 排序。名称按字面包含匹配,查询长度最多 100,页大小为 1 至 100。响应中的 `hasMore` 决定是否提供下一页。查询、详情和删除沿用 `atlas-admin` 客户端与 `atlas-space-admin` 角色鉴权。部署后台镜像前先部署包含列表接口的物品服务,然后在内部入口用管理员与普通账号分别检查权限。

View File

@ -1,13 +1,18 @@
log_format atlas_admin '$remote_addr "$request_method $uri" $status $request_time';
server {
listen 8080;
root /usr/share/nginx/html;
access_log /var/log/nginx/access.log atlas_admin;
include /etc/nginx/admin-identity/*.conf;
location = /healthz { return 200; }
location /api/admin/ {
location ^~ /api/admin/ {
proxy_pass ${ATLAS_GATEWAY_URL};
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
location = /api { return 404; }
location ^~ /api/ { return 404; }
location /assets/ {
try_files $uri =404;
add_header Cache-Control "public, max-age=31536000, immutable";

View File

@ -8,14 +8,16 @@ interface Space extends SpaceSummary { items: number; photos: number }
interface SpacePage { spaces: SpaceSummary[]; hasMore: boolean }
const pageSize = 25
const identityUrl = import.meta.env.VITE_OIDC_URL || 'https://api-atlas.tutudog.com/auth'
const keycloak = new Keycloak({
url: import.meta.env.VITE_OIDC_URL || 'https://api-atlas.tutudog.com/auth',
url: new URL(identityUrl, window.location.origin).href,
realm: import.meta.env.VITE_OIDC_REALM || 'item-atlas',
clientId: 'atlas-admin',
})
const logout = () => keycloak.logout({ redirectUri: window.location.origin + '/' })
const initialized = ref(false)
const authenticated = ref(false)
const authorized = ref(false)
const input = ref('')
const activeQuery = ref('')
@ -33,7 +35,9 @@ const pageNumber = computed(() => pageOffset.value / pageSize + 1)
onMounted(async () => {
try {
await keycloak.init({ onLoad: 'login-required', pkceMethod: 'S256', checkLoginIframe: false })
authorized.value = keycloak.tokenParsed?.atlas_roles?.includes('atlas-space-admin') === true
authenticated.value = keycloak.authenticated === true
const roles: unknown = keycloak.tokenParsed?.atlas_roles
authorized.value = authenticated.value && Array.isArray(roles) && roles.includes('atlas-space-admin')
if (authorized.value) await loadPage(0, '')
else error.value = '当前账号没有空间管理权限。'
} catch {
@ -41,14 +45,34 @@ onMounted(async () => {
} finally { initialized.value = true }
})
function clearManagementData() {
authorized.value = false
page.value = undefined
space.value = undefined
confirming.value = false
confirmation.value = success.value = ''
}
function requireLogin(): never {
clearManagementData()
authenticated.value = false
throw new Error('登录已失效,请重新登录。')
}
async function request(path = '', method = 'GET') {
await keycloak.updateToken(30)
try { await keycloak.updateToken(30) }
catch { requireLogin() }
if (!keycloak.token) requireLogin()
const response = await fetch(`/api/admin/households${path}`, {
method, cache: 'no-store', headers: { Authorization: `Bearer ${keycloak.token}` },
})
if (!response.ok) {
if (response.status === 401) requireLogin()
if (response.status === 403) {
clearManagementData()
throw new Error('当前账号没有空间管理权限。')
}
if (response.status === 404) throw new Error('找不到这个空间。')
if (response.status === 403) throw new Error('当前账号没有空间管理权限。')
throw new Error('操作失败,请稍后重试。')
}
return response
@ -106,8 +130,9 @@ async function deleteSpace() {
if (page.value.spaces.length === 0 && pageOffset.value > 0) {
await readPage(pageOffset.value - pageSize, activeQuery.value)
}
} catch {
} catch (failure) {
page.value = undefined
if (!authorized.value) throw failure
error.value = '空间已删除,列表刷新失败。请重新查询。'
}
}
@ -121,7 +146,8 @@ async function deleteSpace() {
<main>
<header>
<h1>见物 <small>空间管理</small></h1>
<el-button v-if="keycloak.authenticated" text @click="logout">退出登录</el-button>
<el-button v-if="authenticated" text @click="logout">退出登录</el-button>
<el-button v-else-if="initialized" text @click="keycloak.login()">重新登录</el-button>
</header>
<el-alert v-if="error" :title="error" type="error" show-icon :closable="false" />
<el-alert v-if="success" :title="success" type="success" show-icon :closable="false" />

View File

@ -6,6 +6,7 @@
| `helm/item-atlas/` | Kubernetes Helm Chart,部署网关、物品与录入服务 |
| `observability/` | 预发布 Prometheus、Grafana、Alloy、Loki 和 Tempo 的 Helm 配置与安装脚本 |
| [`public/`](public/README.md) | iOS 公网预览的 PostgreSQL、Keycloak、FRP、Nginx 和验收步骤 |
| [`admin-preview/`](admin-preview/README.md) | 管理后台专用的 kind 本机预览与账号权限验收 |
目录内放部署时能直接使用的文件。单个服务或 Web 应用的 Dockerfile 随源码维护。Drone 流水线文件随应用交付放在仓库根目录。提交的配置使用示例值,运行凭证从部署环境注入。

View File

@ -0,0 +1,56 @@
# 管理后台本机预览
在 kind 中创建独立的 `item-atlas-admin-preview` 命名空间。管理员和普通账号由独立的 Keycloak realm 管理。网关和物品服务使用同一次后端候选发布的镜像。PostgreSQL 在一个独立的持久卷上,为登录和物品服务分别创建数据库和用户。
```mermaid
flowchart LR
browser[本机浏览器] -->|127.0.0.1:18482| web[Nginx 与管理后台]
web -->|OIDC 授权码与 PKCE| identity[Keycloak]
web -->|管理 API| gateway[Spring Cloud Gateway]
gateway --> inventory[物品服务]
inventory -->|内网 JWKS| identity
identity --> iddb[(身份数据库)]
inventory --> pg[(物品数据库)]
```
浏览器通过同源 `/auth` 登录,物品服务从集群内获取签名公钥。令牌的 issuer 仍须匹配浏览器地址。管理接口验证签名、有效期、audience、`atlas-admin` 客户端和 `atlas-space-admin` 角色。此配置使用回环 HTTP,公网部署请使用 [HTTPS 身份配置](../../docs/deployment/identity-and-media.md)。
## 启动
在能访问 kind 的终端执行,确认当前上下文、节点镜像架构和存储类位置。已有的候选后端镜像可以直接用。新节点需按 [候选交付流程](../../docs/deployment/backend-release.md) 拉取清单中的两个后端镜像。Docker 和 kubectl 如果同在虚拟机里,以下构建与部署命令也在虚拟机中执行。
```sh
kind_cluster=atlas-dev
context="kind-$kind_cluster"
namespace=item-atlas-admin-preview
secret_dir=/path/on/ssd/item-atlas-admin-preview
docker build --build-arg VITE_OIDC_URL=/auth \
--build-arg VITE_OIDC_REALM=item-atlas-admin-preview \
-t item-atlas-admin:admin-preview-0.1.1 apps/admin
kind load docker-image --name "$kind_cluster" item-atlas-admin:admin-preview-0.1.1
python3 deploy/admin-preview/prepare-secrets.py "$secret_dir"
kubectl --context "$context" create namespace "$namespace"
for component in postgres keycloak inventory; do
kubectl --context "$context" -n "$namespace" create secret generic "atlas-admin-$component" \
--from-env-file="$secret_dir/$component.env"
done
kubectl --context "$context" -n "$namespace" create secret generic atlas-admin-realm \
--from-file="$secret_dir/item-atlas-admin-preview-realm.json"
kubectl --context "$context" apply --dry-run=server -k deploy/admin-preview
kubectl --context "$context" apply -k deploy/admin-preview
kubectl --context "$context" -n "$namespace" get pods,pvc
kubectl --context "$context" -n "$namespace" port-forward --address 127.0.0.1 svc/item-atlas-admin 18482:8080
```
首次部署生成两位预览用户 `preview-admin`、`preview-viewer`,密码在私有目录的 `credentials.json`。保留该目录。已有预览更新镜像后重新执行 `apply -k`,无需重新建 Secret。Keycloak 仅在首次创建 realm 时从文件导入用户。
## 验收和排错
打开 [管理后台](http://127.0.0.1:18482/)。管理员可以分页查空间、按名称或完整 ID 定位、查看物品和照片数量。普通账号登录后会看到权限提示。删除请使用专用测试空间,提交后检查数据库中的 `space_admin_action`。照片记录被删除时,数据库触发器会在同一个事务登记 `media_cleanup`。本预览用于核对队列写入,真实对象清理由 [对象存储冒烟脚本](../../backend/tests/media_smoke.py) 在带存储的环境验收。
页面打不开先查 `/healthz` 和端口转发。浏览器返回登录页时看 Keycloak 回调地址和 Nginx `/auth` 路由。管理 API 返回 `401` 时核对 issuer、JWKS 和有效期,返回 `403` 时核对客户端和管理员角色。物品服务启动时 Flyway 会等待数据库,持续失败时查看 PVC、PostgreSQL 日志及 Flyway 日志。后台 Nginx 的访问日志保留路径、状态码与响应耗时,省略包含授权码的查询参数。
更新后台 Pod 后端口转发会断开,重新运行 `kubectl port-forward` 即可。停止转发后入口关闭,预览数据库保留在 PVC 中。 [端口转发](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_port-forward/) · [Keycloak hostname](https://www.keycloak.org/server/hostname) · [Spring Boot Flyway 配置](https://docs.spring.io/spring-boot/4.0/appendix/application-properties/#application-properties.data-migration)

View File

@ -0,0 +1,97 @@
apiVersion: v1
kind: Service
metadata:
name: atlas-admin-inventory
spec:
selector: {app: atlas-admin-inventory}
ports:
- {name: http, port: 8081}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: atlas-admin-inventory
spec:
replicas: 1
strategy: {type: Recreate}
selector:
matchLabels: {app: atlas-admin-inventory}
template:
metadata:
labels: {app: atlas-admin-inventory}
spec:
automountServiceAccountToken: false
containers:
- name: inventory
image: git.tutudog.com/dongjf/item-atlas-inventory-service:5299e526f4aee1e619a66f3d57e464b05be7ef92
envFrom:
- secretRef: {name: atlas-admin-inventory}
env:
- {name: SPRING_PROFILES_ACTIVE, value: release}
- {name: ATLAS_DB_URL, value: 'jdbc:postgresql://atlas-admin-postgres:5432/itematlas_inventory'}
- {name: ATLAS_DB_USER, value: atlas_inventory}
- {name: ATLAS_OIDC_ISSUER_URI, value: 'http://127.0.0.1:18482/auth/realms/item-atlas-admin-preview'}
- {name: ATLAS_OIDC_AUDIENCE, value: item-atlas-api}
- {name: SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_JWK_SET_URI, value: 'http://atlas-admin-keycloak:8080/auth/realms/item-atlas-admin-preview/protocol/openid-connect/certs'}
- {name: SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE, value: '4'}
- {name: SPRING_FLYWAY_CONNECT_RETRIES, value: '12'}
- {name: SPRING_FLYWAY_CONNECT_RETRIES_INTERVAL, value: '4s'}
- {name: MANAGEMENT_OTLP_METRICS_EXPORT_ENABLED, value: 'false'}
- {name: JAVA_TOOL_OPTIONS, value: '-Xmx192m'}
ports:
- {name: http, containerPort: 8081}
startupProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 5
failureThreshold: 48
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
resources:
requests: {cpu: 100m, memory: 192Mi}
limits: {cpu: '1', memory: 384Mi}
---
apiVersion: v1
kind: Service
metadata:
name: atlas-admin-gateway
spec:
selector: {app: atlas-admin-gateway}
ports:
- {name: http, port: 8080}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: atlas-admin-gateway
spec:
replicas: 1
strategy: {type: Recreate}
selector:
matchLabels: {app: atlas-admin-gateway}
template:
metadata:
labels: {app: atlas-admin-gateway}
spec:
automountServiceAccountToken: false
containers:
- name: gateway
image: git.tutudog.com/dongjf/item-atlas-gateway:5299e526f4aee1e619a66f3d57e464b05be7ef92
env:
- {name: ATLAS_INVENTORY_URL, value: 'http://atlas-admin-inventory:8081'}
- {name: MANAGEMENT_OTLP_METRICS_EXPORT_ENABLED, value: 'false'}
- {name: JAVA_TOOL_OPTIONS, value: '-Xmx160m'}
ports:
- {name: http, containerPort: 8080}
startupProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 5
failureThreshold: 48
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
resources:
requests: {cpu: 100m, memory: 160Mi}
limits: {cpu: '1', memory: 320Mi}

View File

@ -0,0 +1,58 @@
apiVersion: v1
kind: Service
metadata:
name: atlas-admin-keycloak
spec:
selector: {app: atlas-admin-keycloak}
ports:
- {name: http, port: 8080}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: atlas-admin-keycloak
spec:
replicas: 1
strategy: {type: Recreate}
selector:
matchLabels: {app: atlas-admin-keycloak}
template:
metadata:
labels: {app: atlas-admin-keycloak}
spec:
automountServiceAccountToken: false
containers:
- name: keycloak
image: quay.io/keycloak/keycloak:26.8.2
args: [start-dev, --import-realm]
envFrom:
- secretRef: {name: atlas-admin-keycloak}
env:
- {name: KC_DB, value: postgres}
- {name: KC_DB_URL, value: 'jdbc:postgresql://atlas-admin-postgres:5432/itematlas_identity'}
- {name: KC_DB_USERNAME, value: atlas_identity}
- {name: KC_DB_POOL_MAX_SIZE, value: '6'}
- {name: KC_HOSTNAME, value: 'http://127.0.0.1:18482/auth'}
- {name: KC_HTTP_RELATIVE_PATH, value: /auth}
- {name: KC_HTTP_MANAGEMENT_RELATIVE_PATH, value: /}
- {name: KC_PROXY_HEADERS, value: xforwarded}
- {name: KC_HEALTH_ENABLED, value: 'true'}
ports:
- {name: http, containerPort: 8080}
- {name: management, containerPort: 9000}
startupProbe:
httpGet: {path: /health/started, port: management}
periodSeconds: 5
failureThreshold: 60
readinessProbe:
httpGet: {path: /health/ready, port: management}
livenessProbe:
httpGet: {path: /health/live, port: management}
resources:
requests: {cpu: 125m, memory: 384Mi}
limits: {cpu: '1', memory: 768Mi}
volumeMounts:
- {name: realm, mountPath: /opt/keycloak/data/import, readOnly: true}
volumes:
- name: realm
secret: {secretName: atlas-admin-realm}

View File

@ -0,0 +1,8 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: item-atlas-admin-preview
resources:
- postgres.yaml
- keycloak.yaml
- backend.yaml
- web.yaml

View File

@ -0,0 +1,65 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: atlas-admin-postgres-init
data:
10-databases.sh: |
#!/bin/sh
set -eu
psql -U "$POSTGRES_USER" -v ON_ERROR_STOP=1 <<'SQL'
\getenv inventory INVENTORY_PASSWORD
\getenv identity KC_DB_PASSWORD
CREATE ROLE atlas_inventory LOGIN PASSWORD :'inventory';
CREATE ROLE atlas_identity LOGIN PASSWORD :'identity';
CREATE DATABASE itematlas_inventory OWNER atlas_inventory;
CREATE DATABASE itematlas_identity OWNER atlas_identity;
SQL
---
apiVersion: v1
kind: Service
metadata:
name: atlas-admin-postgres
spec:
clusterIP: None
selector: {app: atlas-admin-postgres}
ports:
- {name: postgres, port: 5432}
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: atlas-admin-postgres
spec:
serviceName: atlas-admin-postgres
replicas: 1
selector:
matchLabels: {app: atlas-admin-postgres}
template:
metadata:
labels: {app: atlas-admin-postgres}
spec:
automountServiceAccountToken: false
containers:
- name: postgres
image: postgres:17.12
envFrom:
- secretRef: {name: atlas-admin-postgres}
ports:
- {name: postgres, containerPort: 5432}
readinessProbe:
exec: {command: [pg_isready, -h, 127.0.0.1, -U, postgres]}
resources:
requests: {cpu: 50m, memory: 96Mi}
limits: {cpu: '1', memory: 256Mi}
volumeMounts:
- {name: data, mountPath: /var/lib/postgresql/data}
- {name: init, mountPath: /docker-entrypoint-initdb.d, readOnly: true}
volumes:
- name: init
configMap: {name: atlas-admin-postgres-init, defaultMode: 0555}
volumeClaimTemplates:
- metadata: {name: data}
spec:
accessModes: [ReadWriteOnce]
resources:
requests: {storage: 1Gi}

View File

@ -0,0 +1,112 @@
"""Generate isolated preview credentials and the initial Keycloak realm."""
import argparse
import json
import os
import secrets
from pathlib import Path
def prepare(directory):
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
if directory.stat().st_mode & 0o077:
raise SystemExit('Use a private directory (chmod 700) outside the Git worktree.')
vault = directory / 'credentials.json'
if not vault.exists():
values = {
name: secrets.token_urlsafe(24)
for name in ('postgres', 'inventory', 'identity', 'preview-admin', 'preview-viewer')
}
with vault.open('x') as stream:
json.dump(values, stream, indent=2)
values = json.loads(vault.read_text())
write_env(directory / 'postgres.env', {
'POSTGRES_PASSWORD': values['postgres'],
'INVENTORY_PASSWORD': values['inventory'],
'KC_DB_PASSWORD': values['identity'],
})
write_env(directory / 'keycloak.env', {'KC_DB_PASSWORD': values['identity']})
write_env(directory / 'inventory.env', {'ATLAS_DB_PASSWORD': values['inventory']})
(directory / 'item-atlas-admin-preview-realm.json').write_text(json.dumps(realm(values)))
def write_env(path, values):
path.write_text(''.join(f'{name}={value}\n' for name, value in values.items()))
def realm(values):
origin = 'http://127.0.0.1:18482'
return {
'realm': 'item-atlas-admin-preview',
'displayName': '见物后台预览',
'enabled': True,
'sslRequired': 'none',
'registrationAllowed': False,
'bruteForceProtected': True,
'roles': {'realm': [{'name': 'atlas-space-admin'}]},
'clients': [{
'clientId': 'atlas-admin',
'enabled': True,
'protocol': 'openid-connect',
'publicClient': True,
'standardFlowEnabled': True,
'implicitFlowEnabled': False,
'directAccessGrantsEnabled': False,
'redirectUris': [origin + '/'],
'webOrigins': [origin],
'attributes': {
'pkce.code.challenge.method': 'S256',
'post.logout.redirect.uris': origin + '/',
},
'protocolMappers': [
{
'name': 'Inventory API audience',
'protocol': 'openid-connect',
'protocolMapper': 'oidc-audience-mapper',
'config': {
'included.custom.audience': 'item-atlas-api',
'access.token.claim': 'true',
},
},
{
'name': 'Atlas management roles',
'protocol': 'openid-connect',
'protocolMapper': 'oidc-usermodel-realm-role-mapper',
'config': {
'claim.name': 'atlas_roles',
'multivalued': 'true',
'jsonType.label': 'String',
'access.token.claim': 'true',
},
},
],
}],
'users': [
{
'username': username,
'firstName': 'Atlas',
'lastName': 'Preview',
'email': f'{username}@example.invalid',
'emailVerified': True,
'enabled': True,
'realmRoles': roles,
'credentials': [{
'type': 'password',
'value': values[username],
'temporary': False,
}],
}
for username, roles in (
('preview-admin', ['atlas-space-admin']),
('preview-viewer', []),
)
],
}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('directory', type=Path, help='Private directory outside the Git worktree')
os.umask(0o077)
prepare(parser.parse_args().directory)

View File

@ -0,0 +1,62 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: atlas-admin-identity-proxy
data:
identity.conf: |
location ^~ /auth/realms/item-atlas-admin-preview/ {
proxy_pass http://atlas-admin-keycloak:8080;
proxy_set_header Host 127.0.0.1:18482;
proxy_set_header X-Forwarded-Host 127.0.0.1;
proxy_set_header X-Forwarded-Proto http;
proxy_set_header X-Forwarded-Port 18482;
proxy_set_header X-Forwarded-For $remote_addr;
}
location ^~ /auth/resources/ {
proxy_pass http://atlas-admin-keycloak:8080;
}
location = /auth { return 404; }
location ^~ /auth/ { return 404; }
---
apiVersion: v1
kind: Service
metadata:
name: item-atlas-admin
spec:
selector: {app: item-atlas-admin}
ports:
- {name: http, port: 8080}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: item-atlas-admin
spec:
replicas: 1
selector:
matchLabels: {app: item-atlas-admin}
template:
metadata:
labels: {app: item-atlas-admin}
spec:
automountServiceAccountToken: false
containers:
- name: nginx
image: item-atlas-admin:admin-preview-0.1.1
imagePullPolicy: Never
env:
- {name: ATLAS_GATEWAY_URL, value: 'http://atlas-admin-gateway:8080'}
ports:
- {name: http, containerPort: 8080}
readinessProbe:
httpGet: {path: /healthz, port: http}
livenessProbe:
httpGet: {path: /healthz, port: http}
resources:
requests: {cpu: 10m, memory: 16Mi}
limits: {cpu: 250m, memory: 64Mi}
volumeMounts:
- {name: identity-proxy, mountPath: /etc/nginx/admin-identity, readOnly: true}
volumes:
- name: identity-proxy
configMap: {name: atlas-admin-identity-proxy}