feat: 接通见物公网登录与业务接口
continuous-integration/drone/push Build is passing Details

This commit is contained in:
dongjf 2026-11-26 10:12:35 +08:00
parent 8e7ea4df02
commit 767130488c
10 changed files with 375 additions and 10 deletions

View File

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

View File

@ -7,7 +7,7 @@ metadata:
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
backoffLimit: 3
activeDeadlineSeconds: 65
activeDeadlineSeconds: 660
template:
spec:
automountServiceAccountToken: false
@ -31,9 +31,9 @@ spec:
command: ["/bin/sh", "-ec"]
args:
- |
wget -q -T 5 -O /dev/null http://{{ .Release.Name }}-gateway:8080/actuator/health/readiness
wget -q -T 5 -O /dev/null http://{{ .Release.Name }}-inventory-service:8081/actuator/health/readiness
wget -q -T 5 -O /dev/null http://{{ .Release.Name }}-intake-service:8082/actuator/health/readiness
{{- if .Values.canary.enabled }}
wget -q -T 5 -O /dev/null http://{{ .Release.Name }}-inventory-canary:8081/actuator/health/readiness
{{- end }}
until wget -q -T 5 -O /dev/null http://{{ .Release.Name }}-gateway:8080/actuator/health/readiness \
&& wget -q -T 5 -O /dev/null http://{{ .Release.Name }}-inventory-service:8081/actuator/health/readiness \
&& wget -q -T 5 -O /dev/null http://{{ .Release.Name }}-intake-service:8082/actuator/health/readiness{{ if .Values.canary.enabled }} \
&& wget -q -T 5 -O /dev/null http://{{ .Release.Name }}-inventory-canary:8081/actuator/health/readiness{{ end }}; do
sleep 4
done

44
deploy/public/README.md Normal file
View File

@ -0,0 +1,44 @@
# 见物公网预览
`api-atlas.tutudog.com` 为 iOS 提供 HTTPS。完整路径为公网 Nginx → 两条 FRP STCP → 工作 Mac 的 SSD VM → Kubernetes Service。`/api/` 到网关,`/auth/realms/item-atlas/` 与 `/auth/resources/` 到 Keycloak。身份服务用 Keycloak 的生产启动模式和固定 issuer。账号由内部后台创建,开放注册关闭。
## 应用和数据
在 `item-atlas-public` 命名空间部署,另有 PostgreSQL 持久卷和私有图片桶。物品、录入和身份服务各用独立数据库。先准备环境私密文件,再应用底座及应用 chart。
```sh
kubectl get namespace item-atlas-public >/dev/null 2>&1 || kubectl create namespace item-atlas-public
python3 deploy/public/prepare-secrets.py "$ATLAS_SECRET_DIR" \
--owner "$ATLAS_INITIAL_ACCOUNT" --ollama-url "$ATLAS_INTERNAL_OLLAMA_URL"
```
把生成的各 `.env` 按文件名创建同名 Kubernetes Secret。用 `item-atlas-realm.json` 创建 `atlas-public-realm`,文件键用 `item-atlas.json`。在 Garage 建立 `jianwu-public-photos`,导入 `atlas-public-media.env` 里的应用密钥,只授予该桶的读取和写入权限。镜像仓库通过 `item-atlas-registry` 提供拉取权限。生成文件、用户口令和服务密钥保存在 SSD 上的受控目录。
这些文件用于初始化。已有环境的 Keycloak realm、账号和数据库密码由运行中的服务维护。备份与恢复时,以当前数据库、图片桶和现用 Secret 为准。
```sh
kubectl -n item-atlas-public apply -f deploy/public/base.yaml
kubectl -n item-atlas-public rollout status deployment/atlas-keycloak --timeout=5m
helm upgrade --install item-atlas deploy/helm/item-atlas -n item-atlas-public \
-f deploy/public/values.yaml --set-string image.tag="$ATLAS_PUBLISHED_SHA" \
--atomic --wait --timeout 12m --history-max 10
```
`ATLAS_PUBLISHED_SHA` 取已成功发布镜像的 Drone 构建标识。公网预览使用同一 Helm chart。初次建立该环境时,运行上述 Helm 命令并验收,再配置公网域名。切换版本前先记录当前修订和三个镜像摘要。
## 转发和验收
在集群里用 FRP 客户端直连 `svc/item-atlas-gateway` 和 `svc/atlas-keycloak`。将 `frpc.toml.template` 渲染为受控文件,其中两条 STCP 各用独立密钥。云端 visitor 使用匹配的名称和密钥,只监听 Nginx 容器可达的私有网桥,由 systemd 管理。
```sh
kubectl -n item-atlas-public create secret generic atlas-public-frpc \
--from-file=frpc.toml="$ATLAS_SECRET_DIR/frpc.toml" --dry-run=client -o yaml |
kubectl -n item-atlas-public apply --server-side -f -
kubectl -n item-atlas-public apply -f deploy/public/frpc.yaml
kubectl -n item-atlas-public rollout status deployment/atlas-public-frpc --timeout=2m
kubectl -n item-atlas-public logs deployment/atlas-public-frpc --tail=20
```
日志应显示两个代理注册成功。渲染 `nginx.conf.template`,将两个 `ATLAS_VISITOR_*` 填为实际私有监听地址和端口。用 `nginx -t` 通过后重载。先用 `curl --resolve` 指定目标 IP,核对 TLS、OIDC discovery 和业务 API,再加入公网 A 记录。用公网 DNS 重新测试 iOS 授权码、PKCE 和回调,带令牌查询 `GET /api/households` 应返回 200。另查未登录的 API 及管理路径,预期分别为 401 和 404。 [iOS 验收步骤](../../docs/deployment/identity-and-media.md#ios-公网连通性验收)
工作 Mac 需要挂载 SSD 并运行 Linux VM,集群会启动 FRP 客户端并重连。通常检查顺序是 DNS、TLS、Nginx、STCP、Service 与应用。检查应用版本用 `helm history item-atlas -n item-atlas-public`,回退前先核对数据库迁移兼容性。需要关闭公网预览时停用该域名的独立 Nginx 站点。数据库和私有桶有独立备份流程。

142
deploy/public/base.yaml Normal file
View File

@ -0,0 +1,142 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: atlas-public-db-init
data:
10-atlas.sh: |
#!/bin/sh
set -eu
psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d postgres \
-v inventory="$INVENTORY_PASSWORD" -v intake="$INTAKE_PASSWORD" -v identity="$IDENTITY_PASSWORD" <<'SQL'
CREATE ROLE atlas_inventory LOGIN PASSWORD :'inventory';
CREATE ROLE atlas_intake LOGIN PASSWORD :'intake';
CREATE ROLE atlas_identity LOGIN PASSWORD :'identity';
CREATE DATABASE itematlas_inventory OWNER atlas_inventory;
CREATE DATABASE itematlas_intake OWNER atlas_intake;
CREATE DATABASE itematlas_identity OWNER atlas_identity;
REVOKE CONNECT ON DATABASE itematlas_inventory FROM PUBLIC;
REVOKE CONNECT ON DATABASE itematlas_intake FROM PUBLIC;
REVOKE CONNECT ON DATABASE itematlas_identity FROM PUBLIC;
SQL
---
apiVersion: v1
kind: Service
metadata:
name: atlas-postgres
spec:
selector: {app: atlas-public-postgres}
ports:
- name: pg
port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: atlas-postgres
spec:
serviceName: atlas-postgres
replicas: 1
selector:
matchLabels: {app: atlas-public-postgres}
template:
metadata:
labels: {app: atlas-public-postgres}
spec:
automountServiceAccountToken: false
containers:
- name: postgres
image: postgres:17.12
args: ["-c", "shared_buffers=32MB", "-c", "max_connections=45"]
ports:
- {name: pg, containerPort: 5432}
envFrom:
- secretRef: {name: atlas-public-postgres}
resources:
requests: {cpu: 50m, memory: 96Mi}
limits: {cpu: "1", memory: 256Mi}
readinessProbe:
exec:
command: [pg_isready, -h, 127.0.0.1, -U, postgres]
periodSeconds: 5
timeoutSeconds: 3
volumeMounts:
- {name: data, mountPath: /var/lib/postgresql/data}
- {name: init-db, mountPath: /docker-entrypoint-initdb.d, readOnly: true}
volumes:
- name: init-db
configMap: {name: atlas-public-db-init}
volumeClaimTemplates:
- metadata: {name: data}
spec:
accessModes: [ReadWriteOnce]
resources:
requests: {storage: 4Gi}
---
apiVersion: v1
kind: Service
metadata:
name: atlas-keycloak
spec:
selector: {app: atlas-public-keycloak}
ports:
- name: http
port: 8080
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: atlas-keycloak
spec:
replicas: 1
strategy: {type: Recreate}
selector:
matchLabels: {app: atlas-public-keycloak}
template:
metadata:
labels: {app: atlas-public-keycloak}
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 1000
seccompProfile: {type: RuntimeDefault}
containers:
- name: keycloak
image: quay.io/keycloak/keycloak:26.8.2
args: [start, --import-realm]
securityContext:
allowPrivilegeEscalation: false
capabilities: {drop: [ALL]}
ports:
- {name: http, containerPort: 8080}
- {name: management, containerPort: 9000}
env:
- {name: KC_DB, value: postgres}
- {name: KC_DB_URL, value: 'jdbc:postgresql://atlas-postgres:5432/itematlas_identity'}
- {name: KC_DB_USERNAME, value: atlas_identity}
- {name: KC_DB_POOL_MAX_SIZE, value: '10'}
- {name: KC_HOSTNAME, value: 'https://api-atlas.tutudog.com/auth'}
- {name: KC_HTTP_RELATIVE_PATH, value: /auth}
- {name: KC_HTTP_MANAGEMENT_RELATIVE_PATH, value: /}
- {name: KC_HTTP_ENABLED, value: 'true'}
- {name: KC_PROXY_HEADERS, value: xforwarded}
- {name: KC_HEALTH_ENABLED, value: 'true'}
- {name: JAVA_OPTS_KC_HEAP, value: '-Xms128m -Xmx384m'}
envFrom:
- secretRef: {name: atlas-public-keycloak}
resources:
requests: {cpu: 125m, memory: 384Mi}
limits: {cpu: '1', memory: 672Mi}
startupProbe:
httpGet: {path: /health/started, port: management}
periodSeconds: 5
failureThreshold: 45
readinessProbe:
httpGet: {path: /health/ready, port: management}
periodSeconds: 5
timeoutSeconds: 3
volumeMounts:
- {name: realm, mountPath: /opt/keycloak/data/import, readOnly: true}
volumes:
- name: realm
secret: {secretName: atlas-public-realm}

View File

@ -0,0 +1,19 @@
serverAddr = "ATLAS_FRPS_HOST"
serverPort = 7000
auth.method = "token"
auth.token = "ATLAS_FRPS_TOKEN"
transport.tls.enable = true
[[proxies]]
name = "jianwu-public-api"
type = "stcp"
secretKey = "ATLAS_API_STCP_KEY"
localIP = "item-atlas-gateway"
localPort = 8080
[[proxies]]
name = "jianwu-public-oidc"
type = "stcp"
secretKey = "ATLAS_OIDC_STCP_KEY"
localIP = "atlas-keycloak"
localPort = 8080

34
deploy/public/frpc.yaml Normal file
View File

@ -0,0 +1,34 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: atlas-public-frpc
spec:
replicas: 1
strategy: {type: Recreate}
selector:
matchLabels: {app: atlas-public-frpc}
template:
metadata:
labels: {app: atlas-public-frpc}
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 65532
seccompProfile: {type: RuntimeDefault}
containers:
- name: frpc
image: ghcr.io/fatedier/frpc:v0.69.1@sha256:5a1b2cbcec588f1def1de6c5bc372e5f6783f78a151aecb4aae99fcebb9b573a
args: [-c, /etc/frp/frpc.toml]
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: {drop: [ALL]}
resources:
requests: {cpu: 10m, memory: 16Mi}
limits: {cpu: 200m, memory: 64Mi}
volumeMounts:
- {name: config, mountPath: /etc/frp, readOnly: true}
volumes:
- name: config
secret: {secretName: atlas-public-frpc}

View File

@ -0,0 +1,35 @@
server {
listen 80;
server_name api-atlas.tutudog.com;
return 308 https://api-atlas.tutudog.com$request_uri;
}
server {
listen 443 ssl;
server_name api-atlas.tutudog.com;
ssl_certificate /etc/nginx/ssl/tutudog.com/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/tutudog.com/privkey.pem;
client_max_body_size 6m;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Port 443;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_connect_timeout 5s;
proxy_read_timeout 90s;
location ^~ /api/admin/ { return 404; }
location ^~ /api/ {
proxy_pass http://ATLAS_VISITOR_API;
}
location ^~ /auth/realms/item-atlas/ {
proxy_pass http://ATLAS_VISITOR_OIDC;
}
location ^~ /auth/resources/ {
proxy_pass http://ATLAS_VISITOR_OIDC;
}
location / { return 404; }
}

View File

@ -0,0 +1,82 @@
import argparse
import json
import os
import secrets
from pathlib import Path
parser = argparse.ArgumentParser(description='Prepare the secrets for a new Item Atlas public preview.')
parser.add_argument('directory', type=Path, help='A directory on the SSD outside the Git worktree')
parser.add_argument('--owner', required=True, help='First account username')
parser.add_argument('--ollama-url', required=True, help='Internal Ollama URL')
args = parser.parse_args()
os.umask(0o077)
root = args.directory.resolve()
root.mkdir(mode=0o700, parents=True, exist_ok=True)
vault = root / 'generated.json'
if not vault.exists():
values = {key: secrets.token_urlsafe(30) for key in ('pg', 'inventory', 'intake', 'dbkeycloak', 'admin', 'owner', 'delivery')}
values['media_key'] = 'GK' + secrets.token_hex(12)
values['media_secret'] = secrets.token_hex(32)
vault.write_text(json.dumps(values))
values = json.loads(vault.read_text())
def env(name, data):
(root / (name + '.env')).write_text(''.join(f'{k}={v}\n' for k,v in data.items()))
hostname = 'https://api-atlas.tutudog.com/auth/realms/item-atlas'
internal = 'http://atlas-keycloak:8080/auth/realms/item-atlas/protocol/openid-connect'
issuer = {'ATLAS_OIDC_ISSUER_URI': hostname, 'ATLAS_OIDC_AUDIENCE': 'item-atlas-api',
'SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_JWK_SET_URI': internal + '/certs',
'SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE': 6,
'MANAGEMENT_OTLP_METRICS_EXPORT_ENABLED': 'false'}
env('atlas-public-postgres', {'POSTGRES_PASSWORD': values['pg'], 'INVENTORY_PASSWORD': values['inventory'],
'INTAKE_PASSWORD': values['intake'], 'IDENTITY_PASSWORD': values['dbkeycloak']})
env('atlas-public-keycloak', {'KC_DB_PASSWORD': values['dbkeycloak'], 'KC_BOOTSTRAP_ADMIN_USERNAME': 'atlas-bootstrap',
'KC_BOOTSTRAP_ADMIN_PASSWORD': values['admin']})
for service in ('inventory','intake'):
settings = issuer | {'ATLAS_DB_URL': f'jdbc:postgresql://atlas-postgres:5432/itematlas_{service}',
'ATLAS_DB_USER': 'atlas_' + service, 'ATLAS_DB_PASSWORD': values[service]}
if service == 'intake':
settings.update(ATLAS_OAUTH_TOKEN_URI=internal+'/token', ATLAS_OAUTH_CLIENT_ID='atlas-intake',
ATLAS_OAUTH_CLIENT_SECRET=values['delivery'], ATLAS_OLLAMA_ENABLED='true',
ATLAS_OLLAMA_URL=args.ollama_url, ATLAS_OLLAMA_MODEL='gemma4:12b')
env('item-atlas-'+service, settings)
env('atlas-public-media', {'ATLAS_MEDIA_ENDPOINT': 'http://atlas-media.item-atlas-staging.svc:3900',
'ATLAS_MEDIA_BUCKET': 'jianwu-public-photos', 'ATLAS_MEDIA_REGION': 'garage',
'ATLAS_MEDIA_ACCESS_KEY': values['media_key'], 'ATLAS_MEDIA_SECRET_KEY': values['media_secret']})
audience = {'name': 'item-atlas-api audience', 'protocol': 'openid-connect', 'protocolMapper': 'oidc-audience-mapper',
'config': {'included.custom.audience': 'item-atlas-api', 'access.token.claim': 'true'}}
role_mapper = {'name': 'Atlas public admin role', 'protocol': 'openid-connect', 'protocolMapper': 'oidc-usermodel-realm-role-mapper',
'config': {'claim.name': 'atlas_roles', 'multivalued': 'true', 'jsonType.label': 'String', 'access.token.claim': 'true'}}
native = {'clientId': 'atlas-ios', 'enabled': True, 'protocol': 'openid-connect', 'publicClient': True,
'standardFlowEnabled': True, 'implicitFlowEnabled': False, 'directAccessGrantsEnabled': False,
'attributes': {'pkce.code.challenge.method': 'S256'}, 'defaultClientScopes': ['profile'], 'protocolMappers': [audience]}
admin = native | {'clientId': 'atlas-admin', 'redirectUris': ['https://admin-atlas.tutudog.com/'],
'webOrigins': ['https://admin-atlas.tutudog.com'], 'protocolMappers': [audience, role_mapper]}
profile = {
'name': 'profile', 'protocol': 'openid-connect', 'attributes': {'include.in.token.scope': 'true'},
'protocolMappers': [
{'name': claim, 'protocol': 'openid-connect', 'protocolMapper': 'oidc-usermodel-property-mapper',
'config': {'user.attribute': prop, 'claim.name': claim, 'jsonType.label': 'String',
'access.token.claim': 'true', 'id.token.claim': 'true', 'userinfo.token.claim': 'true'}}
for prop, claim in (('username', 'preferred_username'), ('firstName', 'given_name'), ('lastName', 'family_name'))
],
}
realm = {'realm': 'item-atlas', 'displayName': '见物', 'enabled': True, 'sslRequired': 'external',
'registrationAllowed': False, 'resetPasswordAllowed': False, 'bruteForceProtected': True,
'accessTokenLifespan': 300, 'internationalizationEnabled': True, 'supportedLocales': ['en', 'zh-CN'],
'defaultLocale': 'zh-CN', 'roles': {'realm': [{'name': 'atlas-space-admin'}]},
'clientScopes': [profile, {'name': 'atlas.deliver', 'protocol': 'openid-connect', 'attributes': {'include.in.token.scope': 'true'}}],
'clients': [native | {'redirectUris': ['com.tutudog.itematlas:/oauth2/callback']}, admin,
{'clientId': 'atlas-intake', 'enabled': True, 'protocol': 'openid-connect', 'publicClient': False,
'clientAuthenticatorType': 'client-secret', 'secret': values['delivery'], 'standardFlowEnabled': False,
'directAccessGrantsEnabled': False, 'serviceAccountsEnabled': True,
'optionalClientScopes': ['atlas.deliver'], 'protocolMappers': [audience]}],
'users': [{'username': args.owner, 'enabled': True, 'firstName': '见物', 'lastName': '所有者',
'email': f'{args.owner}@example.invalid', 'emailVerified': False,
'credentials': [{'type': 'password', 'value': values['owner'], 'temporary': False}]}]}
(root/'item-atlas-realm.json').write_text(json.dumps(realm,ensure_ascii=False))
print('Private environment files and realm import prepared.')

View File

@ -0,0 +1,8 @@
mediaSecret: atlas-public-media
imagePullSecrets:
- name: item-atlas-registry
rollout:
maxSurge: 0
maxUnavailable: 1
observability:
otlpTracesEndpoint: http://atlas-alloy.item-atlas-observability.svc:4318/v1/traces

View File

@ -4,7 +4,7 @@
[原图](diagrams/deployment.png) · [draw.io 源文件](diagrams/deployment.drawio)
原图描述正式部署的目标。当前预发布由外置 SSD 上的 ARM64 Lima VM、kind 和内网端口转发承载。云端负责 Git、CI 与制品,工作机 runner 负责镜像和部署,家用 Mac 提供推理。
原图描述正式部署的目标。当前内网预发布和 iOS 公网预览由外置 SSD 上的 ARM64 Lima VM 和 kind 承载,使用独立命名空间和账号数据。云端负责 Git、CI 与制品,工作机 runner 负责镜像和部署,家用 Mac 提供推理。
```mermaid
flowchart LR
@ -44,9 +44,9 @@ Kubernetes 的控制面和应用在同一虚拟机内。Helm 管理应用和可
## 公网入口和域名
公网 Nginx 负责证书和 HTTPS,保留 Host 和转发协议,走回环地址的 frp visitor。工作 Mac 的虚拟机用 STCP 接入现有 frps。集群入口 Nginx 依据 Host 转发到对应 Web Service,`/api` 统一转给 Spring Cloud Gateway。公网访问以 HTTPS 入口为边界,数据库、模型、监控和 Kubernetes 管理端口留在内网。家用 Mac 的模型请求只走家庭私网。 [frp STCP](https://gofrp.org/en/docs/examples/stcp/)
公网 Nginx 负责证书和 HTTPS,保留 Host 和转发协议。iOS 预览的两个 frp visitor 在云端私有网桥监听,分别通过 STCP 到集群中的 Gateway 和 Keycloak Service。数据库、监控和 Kubernetes 管理端口留在内网。见物的模型调用走家庭私网。 [公网预览部署](../../deploy/public/README.md) · [frp STCP](https://gofrp.org/en/docs/examples/stcp/)
子域名统一采用 `用途-产品名`。移动网页用 `m`,PC 网页用 `pc`。以下命名已确定,DNS、证书与转发在部署时配置。iOS 公网路径需要单独验收。 [公网连通性验收](identity-and-media.md#ios-公网连通性验收)
子域名统一采用 `用途-产品名`。移动网页用 `m`,PC 网页用 `pc`。当前已开通 iOS 公网预览的 API 域名,其余三个用于后续 Web 部署。 [公网连通性验收](identity-and-media.md#ios-公网连通性验收)
| 域名 | 指向 |
| --- | --- |