Prepare verified laboratory 7 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:32:06 +03:00
parent 20afc2c790
commit eb1b5c7b84
677 changed files with 208256 additions and 64 deletions
+34
View File
@@ -0,0 +1,34 @@
# Native Grafana acceptance boundary
This phase uses the authorized Grafana13.3.1 image and unmodified ready-made OpenObserve1.0.1 plugin from the coordinator's single verified download. Copy only verified public artifacts into the lab7 namespace. Wait for exact native image/import handover before any stand start. No OpenBao or SII download is authorized. Preserve ZIP361cae, its manifest backup and historical closures; backend112 and its protected source remain unchanged.
Use system-design/test-design/browser-testing. Operational helpers stay TypeScript+Bun and pinned Compose project/manifest; native runs use background.slice on the owned HDD path. Reuse existing request/receipt/secret readers. New unique receipts exclusively claimed before work, preserve primary stage/status/content type, best-effort diagnostics, owned teardown in finally. Never count HTTP200 with empty/error data as acceptance.
| Situation / input class | Example | Expected result | Level |
|---|---|---|---|
| Valid cached image and plugin | Coordinator receipts, SHA and linux/amd64 identities | Freeze own alias and own plugin copy; no second download or source-cache changes | Read-only guard + native |
| Missing or mismatched artifact | Wrong imageID/version/pluginSHA | Stop before credential read or stand start | Guard / negative fixture |
| Exact current source | BACKEND-READY09fe,112files + checked binaries | Initial lease retained through final checks; historical archive untouched | Existing source guard |
| Published Grafana endpoint | grafana-gateway has private+edge networks | Resolve verified owned published127.0.0.1 binding3443; verify actual HTTPS response and CA/SAN | Pure guard + native |
| Wrong HTTPS identity | foreign trust/wrong hostname | Explicit certificate failure with authenticated positive control | Native TLS |
| Native datasources | prometheus + openobserve dedicated querySA | Native API registration/health/query success, no root credential; mTLS query5082 | Native API + browser |
| Metrics | All19 mounted targets in retained historical interval | Each actual response has finite nonempty numeric data, no embedded errors; browser renders panels | Native datasource + browser |
| Logs/traces | Retained trace13aa5cd043d490330a867149fc7f4dbf,42spans/41parents,3logs | Actual ready-made plugin native trace view, correct start/duration/parents; log↔trace navigation | Native plugin + browser |
| Response limits | Below/at/above declared cap through actual consumer | Explicit success/rejection per real Prom proxy/plugin path; do not transfer a generic proxy limit claim to plugin backend | Native boundary |
| Worker incident | Stop own worker, one new unique upload fixture | Original backlog rule observes age>30, pending→firing; worker recovery completes same job and rule resolves | Native application + actual Grafana rule |
| DB incident | Bounded own DB outage + minimal real requests | Original server-error rule sees actual5xx ratio, pending→firing; DB recovery restores normal and resolves | Native application + actual Grafana rule |
| Alert dependency failure | NoData/evaluationError | Preserve actual state; never count it as threshold firing or recovery | Native rule readback |
| Teardown | Failure during any stage | Stop only owned services, retain first error; prove no owned running containers | Native lifecycle |
| Browser context acquired, page creation rejects | Required fake acquire succeeds, fake newPage rejects | Close exactly once, preserve original error | Pure lifecycle factory |
| Browser listener initialization throws | Required fake page exists, listener throws | Close exactly once before propagating primary error | Pure lifecycle factory |
| Browser cleanup also rejects | Primary failure plus failing close/reporter, or normal work plus close failure | Report cleanup separately; retain primary, otherwise reject cleanup error | Pure lifecycle factory |
| Gauge restart history | Same fixed incident timestamp, full labels including start_time, raw120s samples | Old capacity/observer expressions compared with timestamp-filtered native expressions; retained samples identify age without assuming which label changed | Native PromQL, storage only |
| Gauge series absent | Missing service selector at same timestamp | Both filtered aggregates remain NoData, never synthetic0 | Native PromQL |
Failure cases: image/import mismatch, absent plugin executable, failed provisioning/auth, TLS or service DNS failure, empty/NaN frames, wrong historical window, missing/zero-duration trace spans, failed internal links, cap bypass on another consumer, alert NoData instead of Firing, outage not restored, primary failure replaced by teardown or evidence I/O. Cases not yet executed stay pending.
Retained history and newly authorized incidents have separate receipts. The new minimal producer fixture is allowed only to exercise mandatory fresh worker/DB alert incidents. Do not rerun public full smoke/security,120s freshness or old all3 producer merely to repair readback. Operator-rendered credentials/heartbeat remain explicitly not Bao. Actual rule expressions and thresholds are preserved; synthetic vectors or patched thresholds are not incident acceptance.
Native reader correction: /api/datasources is only a list DTO; its missing basicAuthUser/secureJsonFields is not an authentication failure. The actual UID detail reader and matching health endpoint expose/prove the intended values; required fake request ports cover the native list shape, an owner-account mismatch and HTTP200 health with an error body. Production preflight uses the same reader.
A retained historical histogram-rate panel can be NoData after traffic stops even while cumulative histogram queries remain finite. Preserve this outcome. Fresh live19-panel acceptance belongs to the newly authorized incident fixture. Use at most one unique two-member chat and three tiny uploads: the worker outage/restart changes its SDK instance, so an incident job plus a later completion in that same restarted instance supplies two cumulative histogram observations. Generate only bounded real business requests, without repeating the public full smoke suite or substituting alert expressions/thresholds.
+13
View File
@@ -0,0 +1,13 @@
# Grafana13.3.1 initializer and private consumers
The actual cached image is bound to linux/amd64 ID1c88285f1dd391a62232c010e6c224846e6a73bdc583b3365be2eba614b7919e. Its native /run.sh was read before first startup: GF_*__FILE is converted to the file content and the suffixed variable removed; supplying both forms is an error. Our credentials are exact single-file read-only mounts, never command arguments.
Source-binding limitation: actual native health reports build commit da3aa3ff574e7dbbf808c66b6daa744defed0441. The public v13.3.1 tag dereferences to5db6ba887630c7fa12e5bfd063f2fa854025468c. Matching build source is unavailable through the checked public raw/API routes. The tag sources below are reference only, not proof of the compiled build's minimum or strong-password policy. Native successful authentication with the captured64hex admin credential and native UID-detail/health readers are empirical checks on the exact cached image.
The reference-tag [SQLStore initializer](https://raw.githubusercontent.com/grafana/grafana/v13.3.1/pkg/services/sqlstore/sqlstore.go) checks existing users before creating the configured admin. Its [createUser](https://raw.githubusercontent.com/grafana/grafana/v13.3.1/pkg/services/sqlstore/user.go) hashes the provided nonempty password. This reference bootstrap path directly casts the password and does not call the ordinary password-policy validator.
The reference-tag [ordinary password validator](https://raw.githubusercontent.com/grafana/grafana/v13.3.1/pkg/services/user/password.go) and [defaults](https://raw.githubusercontent.com/grafana/grafana/v13.3.1/conf/defaults.ini) describe four-character minimum with strong policy off, or twelve plus character classes when enabled. These constraints are not attributed to the unavailable compiled source. The existing lab7 bootstrap already captured a random256-bit,64hex-character admin password in the encrypted services envelope and exact consumer file in the same process. Before first startup prepareGrafana verifies exact equality without printing either value. No admin password is generated again or implicitly reset.
A separate random256-bit Grafana secret_key is captured in grafana-security.enc before publishing the narrow grafana-secret-key file. Existing encrypted/key bytes are reused with exclusive-or-identical preservation. This replaces the upstream shared default signing/encryption key. Query ServiceAccount remains separate from the Grafana operator and OpenObserve owner. Native account200/403 guards run before Grafana startup. Configuration disables plugin preinstall/update/key retrieval and uses only the frozen artifacts. Cache preparation performs no network download; a universal runtime-egress byte measurement is not claimed.
Current lab7 alert group interval10s matches the native default scheduler minimum10s; no1s scheduler override is needed. Actual alert incident acceptance remains separate from config/source validation.
+48
View File
@@ -0,0 +1,48 @@
# Native Grafana и OpenObserve
Этот документ фиксирует исторический GF-only checkpoint и его provider/dataset. Последующая native Bao/Agent приёмка имеет [отдельный composite](../evidence/openbao/NATIVE-COMPOSITE.json) и [независимый review](../evidence/reviews/OPENBAO-NATIVE-REVIEW.md); старые GF receipts/false flags не переписаны. Текущие approvals и source checks находятся в RUN.md/REPORT.md в корне проекта.
Текущий стек — OpenObserve1.1.2, Collector-k8s0.163.2, Grafana13.3.1 и готовый сторонний unsigned plugin OpenObserve1.0.1. Backend112/SHA09fe не менялся. Все runs выполнены на собственном omarchy HDD stand `mtuci-vp7-security`, с pinned Compose и background.slice. Полный security/Bao/grade5 PASS не заявляется.
Для этого checkpoint пользователь разрешил600000000байт только Grafana/plugin. Единственная загрузка root составила559001001байт; Lab7 проверил cache imageID1c88285f1dd391a62232c010e6c224846e6a73bdc583b3365be2eba614b7919e и plugin ZIP SHAe0c2cbcc7cf6d05bcfaa606db39e52249eb0dd234376e45a3f896353831c2fd5, затем создал собственный alias/copy без второго download. [Cache receipt](../evidence/grafana/cache-freeze-5c2e02c0-ccdd-4a95-a1c1-74cee6d7d408.json). Тогда85МБ OpenBao ещё ожидали согласия; позже оно получено и actual80099233bytes записаны в отдельном Bao checkpoint. СИИ не разрешён ни одной из этих квот.
## Измеренные результаты
| Проверка | Native outcome | Receipt в evidence/grafana |
|---|---|---|
| HTTPS, UID detail и health обеих datasource | Grafana13.3.1/databaseOK, scoped query SA, metrics/plugin health200OK | preflight-1b430ef3-576a-41fd-aeec-91c0e7c36af0.json |
| Original worker backlog rule | Firing61,229с/A60,063806>30; та же job ready, resolved8,331с/A0 | incidents-e80b4c4d-df97-4cc9-b6d4-7ba651e0542b.json |
| Original DB-error rule | 32 instrumented direct-mTLS API5xx; public LB503 не входит в application5xx; firing48,889с/A0,708748>0,05, resolved68с/A0 | тот же incident receipt |
| Девятнадцать панелей в browser | Все native frames непустые с finite samples; без zero-fill | browser-b8b2e8e1-a42d-41c0-bbde-cbcabfd16369.json |
| Native waterfall и оба link clicks |42spans/41parents; выбранный span54d90849005639d4 → HTTP200/одна worker.job с тем же span/trace | browser-86b82122-1952-4da5-b8d1-1a41ff9dcef2.json |
| Response consumers | Browser9МиБ:200/9437661байт RED →502/35байт; backend400/180байт RED →400/144байт; оба small positives200/одна строка | response-consumers-e384107e-200b-4ed2-b2be-c47adb6c1723.json и response-consumers-b8b2e8e1-a42d-41c0-bbde-cbcabfd16369.json |
| Native mTLS framing | Exact8388608байт200; +1/encoding/chunked/unknown502; normalized equal length допускается | response-framing-be70ca46-35ef-4420-965d-20019dfb2061.json |
| Native histogram request | omitted/0:2buckets/sum3;1:1bucket/sum1; negative/1001:400; fraction/string/null/object:422 | histogram-b8b2e8e1-a42d-41c0-bbde-cbcabfd16369.json |
| Публичная TLS identity | positive200 до/после; wrong CA и hostname native curl60 | https-identity-35db454d-556e-494d-8350-9e1837e4e271.json |
| Optional page-history state | Own GET404×2 → обычный UI POST201 → reload того же key GET200;4raw diagnostic events/4expected/0unexpected | browser-35db454d-556e-494d-8350-9e1837e4e271.json |
Все указанные wholecommands завершились exit0 и stop_exit0. Старые FAILED/OBSERVED receipts не переписаны. Исходный browser wrapper оставляет conservative OBSERVED/native_ui=false; отдельные case receipts и этот отчёт связывают фактические результаты, не переименовывая старый wholecommand. Проверка links не повторяла producer, incidents или cap.
[Сохранённые control-plane records](../evidence/grafana/native-control-748a9e0b-f1ae-4b4c-b8ce-ae4e19774cba.json) содержат реальные launch/final exec results для четырёх sessions и source line/hash references. Signal exec API не отдаёт; null/finished_ms не придуманы, event timestamp не выдан за remote finish time. B8 phase явно вложена в preflight96875a3e-2d3a-45f2-9a0b-df0de985e95b; отдельный FAILED7c84f311 — прежняя ca31 попытка, не wrapper B8.
## Историческое окно и корректность данных
Trace13aa5cd043d490330a867149fc7f4dbf взята из сохранённого112 dataset, отдельно от новой минимальной alert fixture. Browser показал native trace waterfall, два сервиса и длительность812,88мс. Отдельный общий logs view содержит3correlated API/worker logs. Реальный reverse link передал окно выбранного `attachment.process`:1794785659919…1794785660468мс. В нём корректно вернулась одна worker.job, timestamp1794785660451568мкс, с тем же span54d90849005639d4; требование трёх строк в этом узком окне было бы ошибкой.
Старый reverse capture b8b2 увидел строку старой левой панели раньше загрузки новой и не является reverse PASS. Исправленный86b8 регистрирует specific response wait перед click, сверяет SQL/from/to с native href и выбранным span, проверяет response/trace/span, затем требует новую DOM-строку. Safe PNG/DOM и их SHA находятся в evidence/grafana; cookies, login inputs и private HTTP bodies туда не копируются.
Metric instant point1794801461224мс и browser range grid различаются. Native browser послал intervalMs15000; ранняя range-проба не нашла finite samples у двух коротких histogram rate targets. Исправленная capture сохраняет wire до validation, ждёт каждую видимую панель и использует конец1794801466224мс, на5с позже, с тем же сохранённым dataset. В этом окне все19frame targets finite. Данные не создавались снова, NoData не подменяется0.
В одной фиксированной точке raw120s matrices подтвердили старую worker series83,224с и свежую2,224с. В данном dataset различались и service_instance_id, и start_time. Старые capacity2/observer0 сменились1/1 после `gauge and(timestamp(gauge)>time()-10)`; pool capacity12→10 с тем же старым worker2. Absent selectors остаются NoData. [Gauge proof](../evidence/grafana/gauges-4fc181c9-7bed-4e1f-9d43-eb69474ee891.json), [pool proof](../evidence/grafana/pool-a63697ff-c000-4d91-a8f7-60c4c6821fba.json). SDK export interval2с/timeout1с проверен в immutable backend source. Это configurable engineering freshness window, а не преподавательская константа или универсальный latency bound; freshness остальных gauges этим не заявляется.
## Source и пределы проверок
Actual Grafana health сообщает commitda3aa3ff574e7dbbf808c66b6daa744defed0441, отличный от public tag. Initializer/password tag source остаётся reference only; native64hex admin authentication измерена отдельно. [Initializer boundary](GRAFANA-INITIALIZER.md).
Page-history404 классифицирован только для собственного route `/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/grafana-page-history:fg4fpuerxx79cb`. Shipped JS/map из того же immutable image подтверждает fetchResource404→null/showErrorAlert:false и обычный30с throttle→create/patch. [Локальная source binding копия](reference/grafana-history/history-source-binding.json) содержит byte hashes и отдельно помеченную lab6 provenance; собственные201/200 получены в Lab7. Это не blanket404 whitelist и не заявление о raw console0.
HAProxy response guard ограничивает распознанные native identity/Content-Length ответы перед Grafana browser proxy. GF_DATAPROXY_RESPONSE_LIMIT отдельно проверен на Go backend плагина; он один не ограничивал browser proxy. Input size64КиБ, field size0…1000/missing и bounded time window не являются SQL result-row/work, RAM, decompression или абсолютным timeout cap. Plugin/source/dependencies не патчились.
Operator-provider files и heartbeat этого checkpoint не считаются OpenBao. На тот момент native Bao/rotation, scans и остальные security gates ещё были открыты; их поздние scopes находятся в текущем REPORT/composite, а full DoS/teacher grade не заявлены. Private datasets/профили сохранены вне source/build/package; owned running containers0. Исторические full source checks:100TS,95unit tests/287assertions, formatter0, public source check0. После lifecycle fix: type102, отдельно6fake tests/19assertions и formatter0; исходные95test:unit/frozen receipts не переписаны. Это source-only newPage/listener failure fix через required-port factory; live cases не повторялись. Native existing-user PATCH run не заявляется.
[Independent current39 source review](../evidence/reviews/review-grafana13-lab7-implementation.md), SHA665345febb8abf4fbe6a731127644b5dec88b7594588f991197e734466c6a4f9, завершён SOURCE_PASS: GF7-LIFECYCLE-1 CLOSED, открытых подтверждённых findings в scope нет. Рецензент независимо проверил9lifecycle tests/26expect, retained bytes/control-plane records и выбранные PNG; stand сам не запускал. Это не full security/Bao/grade5 и не archive byte-review. Последующие doc/archive и native Bao reviews имеют отдельные immutable результаты; ZIP361/ca313 остаются историческими.
+30
View File
@@ -0,0 +1,30 @@
# Native OpenBao2.7.2 completion cases
Use existing checked112 source/binaries with native OpenBao/Agent and cached OO/Grafana/Collector. Historical source515/ZIPca313 remains unchanged; canonical Dockerfile build is a separate gate. User approved at most85000000 new artifact bytes only for pinned Bao2.7.2 on omarchy; actual verified download80099233, including registry/config metadata.
| Situation | Expected outcome | Verification |
|---|---|---|
| Removed file storage on2.7.2 | Native startup rejects unknown storage type file; no init attempted | Retained failed bootstrap/startup logs |
| Persistent single-node replacement | Native PebbleDB under /bao/data/pebbledb, non-dev, no appPG sharing or new image | Real HTTPS init, restart/unseal and retained KV |
| Init material |3shares/threshold2 and root token captured encrypted in same process before further action | Native initializer and private envelope guard |
| API/worker policy | Own secret200, foreign/admin403, scoped renewable token, revoked token denied | Native auditBao |
| Canonical runtime preparation | Existing build path remains explicit | Required-port decision test |
| Checked-cache runtime preparation | Verify exact source/image/three binaries, no implicit build or pull | Required-port decision tests + real image hashes |
| Cache verification rejects | Propagate primary failure, never build as fallback | Required fake ports |
| Sealed Bao fault | Every initially fresh running API/worker has post-seal secret_freshness_failed event AND exit/restart; unrelated/old events rejected | Required fake-port RED/GREEN before the one native seal case |
| Recovery | Native unseal/Agent fresh render, both APIs ready and real worker attachment processed | Native API/worker recovery |
| Both replica failures | Read each current-operation receipt and bind stopped alias/container to current attempt; old receipt rejected | Required fake-port RED/GREEN and actual public hooks |
| Source deployment without .git | Require canonical Mac Git query/HEAD/empty result proof pinned by SHA in the native operation lease; verify the same operational source entryset and every raw hash | Required-port producer/reader RED/GREEN and real canonical Git producer |
| Missing/changed/foreign-generation Git proof | Fail closed before native acceptance; never infer zero tracked secrets from absence of .git | Required fake ports |
| Worker compromise | Real queued jobs survive token/cert/S3-secret revocation and replacement | Native track1 scenario |
| Replica alias in tmpfs | Read the current process UUID through exec in its immutable owned container; do not use docker cp for tmpfs | Required-port regression plus native failover |
| Alias read races a restart or returns malformed data | Reject changed container/start time, foreign ownership, stopped process or non-UUID result before stopping any replica | Required fake ports |
| Native revoked-certificate alert | Accept exact ERR_SSL_SSLV3_ALERT_CERTIFICATE_REVOKED as client denial; timeout and an application success still fail | Classifier RED/GREEN plus the native same-identity continuation |
| Interrupted worker rotation | Bind the failed parent, native audit and exact three queued DB IDs/checksums before resuming secret/leaf recovery; verify the same S3 originals without replacing uploads or changing auth | Native partial-state capture and remaining-stage acceptance |
| Unseal precedes the next Docker health tick | Wait for the same owned Bao container to become healthy before Compose starts its dependants; stale unhealthy cannot be treated as a new seal failure | Required clock/read/sleep ports and native recovery |
| Recovery fails after a successful seal rejection | Save the fresh baseline, named cause/exit observations and public503 outcome before recovery starts; preserve the primary failure | Immutable phase evidence |
| Worker Agent remains in sealed-server retry backoff after API readiness | Controlled Agent restart and bounded actual post-seal render check for API1/API2/worker; stale/malformed/future files never count as recovery | Pure freshness predicate, required clock/read/sleep ports and native recovery upload |
| Shared HTTP login limiter | Ten concurrent pairs through two verified mTLS replica endpoints:10 accepted,10 application429 with Retry-After; separate account controls succeed | Required-port case oracle and native HTTP, maximum2 inflight |
| Independent replica limits, wrong alias/actor, unexpected503 or missing429 header/body | Reject before dependent controls; never count an HTTP error as throttling | Pure negative controls; native failures retained privately |
The file-backend failure is confirmed by native output and the official2.7 release/deprecation documentation. PebbleDB is the minimal durable single-server replacement supported by the pinned version; no HA claim is made. Sources: https://openbao.org/blog/release-v2-7-0/ and https://openbao.org/docs/configuration/storage/pebbledb/ . The prior config's disable_mlock is also reported as an unsupported field by the native binary and is removed rather than claimed effective.
+98
View File
@@ -0,0 +1,98 @@
# Lab7 OpenObserve storage migration
## Approved scope and preserved boundary
User authorized replacement of Prometheus/Loki/Tempo storage with OpenObserve. Grafana, OTel Collector, non-dev OpenBao, app PostgreSQL, S3, Valkey, both API replicas and worker remain mandatory. A byte snapshot of root's shared boundary is `OPENOBSERVE-SHARED-BOUNDARY.md` beside this document; it owns the exact shared native ingest/query contract and Grafana integration decision. Backend112 remains byte-identical to BACKEND-READY19:04:33.200Z / SHA09fe19253582282e489406600f3ee20c1e52d786778d6ce90f9d9da4146e5609.
The accepted ZIP8e15/361/ca313 and their source/runtime/review evidence stay historical. OpenObserve passed scoped native bootstrap/all3/persistence/mTLS/query checks; Grafana19panels/trace links/two original alert incidents/response boundaries have separate historical provider receipts in GRAFANA-NATIVE.md. Native OpenBao2.7.2/PebbleDB/Agent, rotation/expiry/seal/recovery and bounded sharedHTTP429 now have a separate accepted composite in ../evidence/openbao/NATIVE-COMPOSITE.json. No failed whole command or former operator provider was relabeled. Final delivery docs/archive review is separate; full security/whole telemetry/teacher grade remain unclaimed. Approved quotas:600000000bytes Grafana/plugin(actual559001001once) and85000000OpenBao(actual80099233); SII is not authorized by either. Azur services/credentials/cache ownership are unchanged.
The local shared-boundary and native-identity files are byte-identical historical contract snapshots. Their then-pending download/gateway labels preserve producer provenance and are not current permission/status instructions; use RUN.md/REPORT.md and the Lab7 composite for the current state. They do not require a sibling workspace at runtime.
Root approved one isolated single-node OpenObserve per lab using its own persistent local data/metadata volume and native default organization. This is a temporary coursework default. No Azur S3/Litestream/NATS/etcd topology or credentials are carried over. API/worker keep their existing OTLP HTTP/protobuf endpoint and mTLS roles; no OpenObserve secret is added to their OpenBao KV or app mounts.
Temporary internal names follow existing service conventions: `openobserve` and `openobserve-gateway`. Actual native ports, route allowlists, auth principal provisioning, Collector secret-file consumers and plugin provisioning must be verified before generated runtime configuration is accepted. Metrics use native Grafana Prometheus querying; normalized series/streams come from the checked live lab6 ingest contract, not the previous messenger Prometheus namespace.
The ready-made third-party plugin is Windforce17/openobserve-grafana-plugin v1.0.1 commit e10214739827dda9318705d49db262b28d67bcfe, Apache2, Grafana>=12.4, unsigned. Its unmodified frontend native trace frame and actual Grafana waterfall/links were checked; generic Go backend tables are not used as waterfall proof. Native auth and separate browser/backend response cases are in GRAFANA-NATIVE.md. It is not the official OpenObserve plugin. Unsigned loading is restricted to this exact checked plugin ID; no shim or dependency patch is introduced.
## Write boundary
Permitted changes: own topology/config generation, telemetry gateways/PKI roles, Collector exporters, Grafana provisioning/dashboard/alerts, bootstrap only for actual new consumers, trust matrix, owned tests/docs/evidence and a newly verified source package. Preserve source leases, exclusive historical evidence and FIRST-snapshot archive guards. No backend source writes, no predecessor bulk sync, no original public contract/test changes, no production publish or external messages.
Collector and Grafana use distinct client identities. Collector may ingest only; Grafana may query only within the isolated organization. Native OpenObserve permissions must be measured, with exact native gateway paths enforcing restrictions if community roles are broader. No root/admin credential is placed in Grafana. The raw storage listener remains loopback-only in its gateway namespace, with no externally published port or plaintext cross-container fallback. Actual credential files and generated private provisioning remain outside Git/build/log/evidence payloads.
## Cases before code
| Situation / input class | Example | Expected result | Level |
|---|---|---|---|
| Storage replacement | generated manifest | Exactly one OpenObserve; old three stores and their gateways absent | Pure generator regression |
| Mandatory neighbors | API/worker/PG/S3/Valkey/Collector/Grafana/Bao | All retained; unchanged app OTLP/file contracts and backend hashes | Generator + source lease |
| Persistent isolation | OpenObserve restart | Dedicated local volume, independent of appPG/Azur; retained own signals | Native restart/query |
| Allowed ingestion | controlled API upload and worker | All three signal payloads queryable with same trace/span context | Native OTLP/query |
| Allowed query | dedicated Grafana principal | Metrics/logs/real trace frame and log↔trace links resolve current data | Native Grafana |
| Untrusted transport | no cert, foreign CA, wrong SAN, expired leaf | Specific TLS/identity denial with positive controls; no timeout-as-denial | Native mTLS matrix |
| Trusted wrong role | app/worker on storage, Grafana ingest, Collector query/admin | Denied despite same CA; correct role succeeds | Native gateway/OO |
| Wrong credentials/org | rejected password, foreign organization | Explicit auth/authorization denial; no shared root/admin principal | Native auth |
| Closed local hop | storage raw port from another namespace | Refused; no app/storage port publication | Native network |
| Bounded outage | OpenObserve stopped | Core messaging works; SDK/Collector buffers/RAM bounded; recovery observed | Native failure/recovery |
| Alert transitions | worker backlog/API failure | Provisioned native engine firing then resolved using measured names/units | Native rule/state |
| Secret failure | credential read/render denied | Fail closed, fixed primary error/stage, no diagnostic leak | Fake-port + native |
| Regression boundary | backend112 / old ZIP8e15 | Exact hashes unchanged; new evidence never overwrites accepted history | Source/artifact guards |
Failures to cover: unavailable storage, startup/auth failure, partial credential provisioning, oversized/timeout query, retry duplication, missing signal fields, plugin/server incompatibility, old native metric-name assumptions, restart during ingest, stale exporter queues, wrong TLS identity, expired/revoked certificate and failed evidence I/O. Native Bao render/renew/seal/rotation remains required separately; operator heartbeat evidence is not its substitute.
## Historical initial inventory and next gates
Read-only Docker image inventory under the current operator finds only Alertmanager among OpenObserve/Collector/Grafana/OpenBao/telemetry names. This does not prove absence in another containerd cache. Native ctr exists; root coordinates privileged cache inspection/digest discovery without starting Azur. No layers or plugin artifacts have been downloaded by this worker.
Implementation starts with metadata-only RED against the actual existing generator. Runtime routes, plugin/auth configuration and image pins follow the root checked boundary. Native images/UI, all three signals, alert transitions, complete mTLS/least privilege/Bao acceptance and independent final review remain pending.
## Native account provisioning cases before code
The verified native identity contract is copied byte-identically as OPENOBSERVE-NATIVE-IDENTITIES.json beside this document, SHA a96ee905c87ca284a8c71f662e1d1034354c525e08e8215078bd63ea7da23a8d. OSS human-user creation forces Admin and is not used. Separate service accounts are nonadmin but both can read/write natively; the two certificate/method/path listeners provide the split. Tokens must be captured privately in the same process before another account request.
| Account situation | Expected outcome | Level |
|---|---|---|
| Valid native HTTP200/code200/user/token | Save exact own token before returning success | Required fake ports then native |
| HTTP401/403/500 or embedded non200 code | Static failure; no credential publication | Required fake ports |
| Missing/empty/oversized token or unexpected user | Fail closed; no invalid Grafana credential | Required fake ports |
| Token persistence failure | Preserve failure; do not provision next identity | Required fake ports |
| Existing saved account | Reuse verified own bytes; do not rotate implicitly | Native workflow |
| Query SA sends ingest / Collector SA sends query | TLS or explicit gateway denial, correct path200 around negative | Native gateway |
Native schema copied from checked lab6 ingestion: logs/traces messenger; trace parent reference_parent_span_id; start_time/end_time nanoseconds; duration/_timestamp microseconds. Histogram bases are http_duration/job_duration/time_to_ready and counter http_requests/jobs_processed, with no legacy exporter namespace or invented _total/unit suffix. Grafana dashboard expressions now follow these names. The optional plugin duration shortcut remains unused.
## Query serialization regression
Current112 all3 session failed at native readback because the authored URI guard rejected plus in the native URLSearchParams serialization of a spaced PromQL query. The command exited1 and stopped its stand. This was a helper failure after app smoke, not a successful whole-session acceptance.
| Input class | Expected behavior | Level |
|---|---|---|
| URLSearchParams PromQL with spaces | Accept serialized plus before any credential read | Pure validator regression |
| Foreign absolute URL or organization | Reject fixed code | Pure validator regression |
| Raw CR/LF, fragment, unencoded path space | Reject fixed code | Pure validator regression |
| Persisted actualSDK trace/log/metric data after helper fix | Query existing native data; do not repeat successful smoke | Native readback/persistence |
Native readback then exposed HTTP422 with a plain deserialize error for the explicit instant-query time parameter. Preserve the HTTP outcome independently of JSON parsing: error-status text bodies retain status/data=null; successful JSON stays parsed; a successful non-JSON response fails with its HTTP code. These three classes are pure response-boundary regressions. The raw native response stays private; query-time grammar must follow the measured native consumer.
The second failure was isolated further: native error markers are floating-point/expected-i64, and the actual filesystem mtimeMs1794785761292.7983 produces fractional search start_time1794784861292798.2. Instant PromQL time grammar was not the cause established by that response and remains unchanged. Native search bounds need integer microseconds.
| Native search bounds case | Expected | Level |
|---|---|---|
| Actual fractional filesystem timestamp | Quantize to integer microseconds before native JSON serialization | Pure producer-boundary regression |
| NaN/infinity/negative/unsafe integer | Fixed rejection before request | Pure regression |
| Inverted/zero/over1hour window | Fixed rejection | Pure regression |
| Valid current window | Same integer microseconds on JSON roundtrip | Pure regression |
## Historical storage-only phase closure
Native receipts and historical failed commands are described in STATUS.md.85TS,63unit tests/206expect and nonwriting formatter passed. Exact current gateway policy was parsed by native HAProxy and passed23 native query cases; TLS2listener identity/trust tests passed separately. No native Grafana rendering/alert transitions or Bao acceptance is implied. The old Prometheus/Loki/Tempo config files remain unmounted historical source; manifest/topology determine current consumers.
The canonical shared-decision origin is workspace vp/OPENOBSERVE-BOUNDARY.md. The package uses its local byte snapshot, OPENOBSERVE-SHARED-BOUNDARY.md; it does not require the sibling workspace at runtime. OPENOBSERVE-NATIVE-IDENTITIES.json preserves the public producer contract byte-for-byte, so its original evidence field is provenance for lab6. Local OPENOBSERVE-NATIVE-SCHEMA.json copies only the measured field names/version/schema consumed here and binds the exact original public contract SHA; authorization/credential fields are omitted. Own lab7 evidence links are resolved from STATUS.md.
## Historical independent-review correction checkpoint
The initial65-path source review is retained unchanged in evidence/openobserve/review-final-source.json. Three bounded corrections had a separate delta: numerator-only error fallback (native healthy0/positive0.2/all-absentNoData), fixed historical SQL/PromQL snapshot end through required fake ports, and saved-account native startup guards before derived publication. That historical checkpoint had88TS and79unit tests/243assertions; exact failures/controls and native existing-account200/403 proof remain in docs/OPENOBSERVE-REVIEW-FIX-CASES.md and retained evidence. No new producer or service account was created for that correction. Its then-pending Grafana/Bao gates are superseded only by their separately scoped later receipts.
## Native Grafana phase
The current storage stack is OpenObserve1.1.2 + Collector-k8s0.163.2 + Grafana13.3.1 with the unmodified ready-made OpenObserve1.0.1 plugin. Native19-panel content, trace42 waterfall/links, both original alert incidents and actual8MiB response consumers have separate measured receipts. See [GRAFANA-NATIVE.md](GRAFANA-NATIVE.md); earlier source/available-native/ZIP361 checkpoints above are historical. Backend112 remains unchanged. Later native Bao/Agent accepted phases and CLI portability are linked by [the review wrapper](../evidence/reviews/OPENBAO-NATIVE-REVIEW.md); current source checks123TS/178tests420/fmt0 and all limitations are in [REPORT.md](../REPORT.md). No whole-grade/full-security or fresh canonical build claim is added.
+14
View File
@@ -0,0 +1,14 @@
{
"status":"native service-account creation and role probes verified; gateway enforcement pending",
"checkedAt":"2026-11-15T23:13:48.522Z",
"sourceCommit":"d16d693ba99bc20621a58b948ecbcad7ec7fa882",
"ownerBootstrap":{"environmentKeys":["ZO_ROOT_USER_EMAIL","ZO_ROOT_USER_PASSWORD"],"passwordPolicy":{"minCharacters":8,"maxCharacters":128,"requires":["ASCII lowercase","ASCII uppercase","ASCII digit","one other character"]},"generator":"Aa1! plus two random UUIDs; actual credential private, never printed"},
"nativeCreate":{"method":"POST","path":"/api/{org}/service_accounts","request":{"email":"unique synthetic email","first_name":"label","last_name":"label"},"responseFields":["code","message","token","user"],"verifiedHTTP":200,"verifiedCode":200,"tokenCapture":"same process, exclusive file creation, private parent0700/file0600 before readback","persistedRole":"service_account","revokeRoute":"DELETE /api/{org}/service_accounts/{email}","adminRotateRoute":"PUT /api/{org}/service_accounts/{email}?rotateToken=true"},
"doNotUseHumanUserCreate":{"path":"POST /api/{org}/users","reason":"OSS handler forcibly assigns Admin even if viewer/user requested"},
"measuredRights":{"ingestPrincipal":{"role":"service_account","searchHTTP":200,"ingestHTTP":200,"adminRotateHTTP":403},"queryPrincipal":{"role":"service_account","searchHTTP":200,"ingestHTTP":200,"adminRotateHTTP":403},"nativeReadOnly":false,"nativeIngestOnly":false},
"collectorCredential":{"principal":"dedicated ingest service_account","header":"Authorization","format":"Basic base64(user:token), exact raw file bytes without terminal newline or CR/LF","fileSubstitution":"${file:/run/secrets/openobserve_ingest_auth}","fileOutsideGitAndBuildContext":true,"reload":"restart Collector after credential update; config parse does not prove export succeeds"},
"grafanaCredential":{"principal":"dedicated query service_account, never root/admin","backendSettings":["basicAuth=true","basicAuthUser","secureJsonData.basicAuthPassword"],"queryGatewayRequired":true,"doNotLabelNativeRoleReadOnly":true},
"images":{"openobserve":{"alias":"docker.io/library/mtuci-vp6-openobserve-cache:v1.1.2","imageId":"sha256:26618f379c86b253c0d91624c487dd14b71293699845ecbc8457c94dca14819f","version":"1.1.2","architecture":"linux/amd64"},"collector":{"alias":"docker.io/library/mtuci-vp6-collector-cache:0.163.2","imageId":"sha256:a65df9129a5b3f99ee4434c5e53aee1965ff0129eda6a2da75ea917165b7fa6b","version":"0.163.2","distribution":"k8s","architecture":"linux/amd64"},"probePullPolicy":"never; normalized alias/digest verified through native inspect before run"},
"evidence":"evidence/openobserve/native-identities.json",
"sourceFiles":["src/config/src/utils/password.rs","src/api/management/src/request/users/mod.rs","src/api/management/src/request/service_accounts/mod.rs","src/common/src/meta/service_account.rs","src/common/src/meta/user.rs"]
}
+85
View File
@@ -0,0 +1,85 @@
{
"origin": "vp/lab6/OPENOBSERVE-CONTRACT.json (public measured contract, not private credentials)",
"source_sha256": "fa449fe01c1aa48abeedbe3246b15d0e7fa7ae6128d0140ae5e32031e81dc539",
"scope": "measured lab6 schema; own lab7 acceptance is linked separately in STATUS.md",
"openobserve": {
"version": "1.1.2",
"organization": "default"
},
"collector": {
"version": "0.163.2",
"distribution": "opentelemetry-collector-k8s"
},
"logs": {
"stream": "messenger",
"timestamp": "_timestamp",
"body": "body",
"event": "event",
"requestId": "request_id",
"traceId": "trace_id",
"spanId": "span_id",
"service": "service_name",
"severity": "severity",
"outcome": "outcome"
},
"traces": {
"stream": "messenger",
"traceId": "trace_id",
"spanId": "span_id",
"parentSpanId": "reference_parent_span_id",
"parentTraceId": "reference_parent_trace_id",
"operation": "operation_name",
"service": "service_name",
"status": "span_status",
"start": "start_time",
"end": "end_time",
"duration": "duration",
"timestamp": "_timestamp"
},
"metrics": {
"counterNames": [
"http_requests",
"jobs_processed",
"database_observer_failures",
"process_cpu"
],
"histogramBases": [
"http_duration",
"job_duration",
"time_to_ready",
"db_pool_acquire_duration"
],
"histogramSuffixes": [
"_bucket",
"_count",
"_sum",
"_min",
"_max"
],
"gauges": [
"queue_depth",
"queue_oldest_age_seconds",
"db_pool_used",
"db_pool_capacity",
"db_pool_pending_acquires",
"worker_busy",
"worker_capacity",
"go_heap_bytes",
"process_resident_memory_bytes",
"database_observer_up",
"ready_slo_matured_10s",
"ready_slo_matured_30s",
"ready_slo_matured_300s",
"ready_slo_timely_10s",
"ready_slo_timely_30s",
"ready_slo_timely_300s"
],
"resourceLabels": [
"service_name",
"service_instance_id",
"service_version",
"deployment_environment_name"
]
},
"credential_fields_copied": false
}
+18
View File
@@ -0,0 +1,18 @@
# Bounded review corrections before code
The previous65-file review manifest remains historical. Three confirmed deltas are authorized; other frozen source stays unchanged. No new service account, app producer or full smoke is required.
| Input class | Expected outcome | Boundary |
|---|---|---|
| Actual stored2xx samples, absent5xx label | Native configured ratio evaluates to finite0 | Existing OpenObserve PromQL |
| Present error/total vector2/10 | Same native arithmetic yields0.2, fallback does not suppress errors | Native query-only fixture |
| Historical parent older than3h | Actual produced SQL start/end stay in the fixed15m snapshot; PromQL time uses the same explicit snapshot end | Required request/clock fake ports |
| Fresh reader with omitted snapshot end | One explicit fake now supplies SQL and PromQL end | Required fake ports |
| Saved expected ingest/query accounts, native200 and admin-deny403 | Publish derived consumer files only after both accounts pass | Required workflow ports, then existing own accounts |
| Wrong token401, unavailable503, unexpected positive201 | Fail closed; no derived publication | Required fake workflow ports |
| Unexpected admin status200/503 | Fail closed; no derived publication | Required fake workflow ports |
| Root/foreign principal, malformed token or extra owner slot | Reject shape before native request/publication | Required fake workflow ports |
Failure status/request kind remain primary and private raw responses stay captured before decoding. Startup validation does not make application health depend on telemetry after startup. Existing native receipts remain valid for their original scope; no retroactive PASS is assigned to failed commands.
All HTTP series absent must remain NoData. The zero fallback belongs only to the error numerator, never around the entire fraction. Native mathematical controls use queries only, without ingesting synthetic telemetry.
+53
View File
@@ -0,0 +1,53 @@
# OpenObserve migration boundary
User scope: replace Prometheus/Loki/Tempo storage in lab6 and lab7. Keep the original mandatory OTel Collector, Grafana, OpenBao, business API, PostgreSQL, Valkey, S3, worker and security criteria. Existing immutable archives/receipts remain historical; new configuration requires its own acceptance.
## Ownership
- Lab6 author: builtin VP, including its isolated remote6 and vp/STATUS.md.
- Lab7 author: HC t67, infrastructure only; backend112 and protected19 remain byte-identical.
- Root: this boundary, cross-subject plan and native Grafana integration acceptance.
- Independent source reviewer: builtin SII; no implementation writes.
## Shared configuration defaults
Use one isolated single-node OpenObserve instance per lab, persistent local data/metadata volume independent of application PostgreSQL. This is a temporary engineering default for the coursework, not the S3/Litestream topology of azur-games. Do not add NATS/etcd or copy Azur credentials/configuration blindly. No telemetry data migration is required from the not-yet-run old storage stack; retain historical source and manifests.
API and worker keep their current OTLP HTTP/protobuf interface and W3C propagation. The Collector forwards logs, metrics and traces through native OTLP to OpenObserve. Authentication is file/environment based outside Git, images and diagnostics. No OpenObserve secret belongs to application code or API/worker OpenBao KV. Start with the isolated native default organization; record exact stream names and native normalized metric names after live ingestion instead of assuming the old Prometheus exporter namespace/suffixes.
Native lab6 export confirmed that the Collector file provider preserves terminal newlines in a header scalar. Generated Authorization header files must contain no CR/LF; configuration validation alone did not detect the invalid wire header. Keep prior failed bytes private and validate authenticated positive export after writing the corrected file.
Lab6 implements the shared OTLP routes/field names and sends a narrow checked artifact contract to lab7. Lab7 retains its TLS/mTLS gateway architecture and updates the declared telemetry matrix, identity allow/deny tests and any actual provisioning consumer. Do not bulk-copy backend or all lab6 configs into lab7.
## Grafana query path
Grafana remains in both labs. Metrics use its native Prometheus data source against the documented OpenObserve Prometheus-compatible organization endpoint. Logs and trace rendering use an existing OpenObserve data source plugin, not an authored protocol shim/plugin.
The official openobserve/openobserve-grafana-plugin current source confirms logs/metrics, not a native trace frame. The ready-made third-party Windforce17/openobserve-grafana-plugin v1.0.1 candidate is pinned to commit e10214739827dda9318705d49db262b28d67bcfe, Apache-2.0, requires Grafana>=12.4.0 and is unsigned. It is not an official OpenObserve release. Its actual frontend trace_id path creates a canonical Grafana trace frame and internal log/trace links; its generic backend table frames are not a substitute for that frontend route. Independent authentication/limits review and a native Grafana rendering check remain required before accepting it.
Independent source probes confirm the canonical nanosecond span path, but exposed conditional defects in the microsecond `_timestamp` fallback (factor1000) and ignored custom duration-field setting. Inspect actual native OpenObserve trace columns and enforce a correctly rendered canonical start/end/duration path; do not accept an empty or zero-duration waterfall and do not add a custom shim or silently patch the dependency. Bound Grafana data-proxy response size/time and actual query results as well as the Collector.
The pinned OpenObserve1.1.2 decoder (commit d16d693ba99bc20621a58b948ecbcad7ec7fa882) preserves native `start_time`/`end_time` in nanoseconds, `_timestamp` and `duration` in microseconds. The plugin's normal native start/end path is source-proven compatible; inspect real rows before acceptance. Its optional duration-search shortcut applies nanoseconds to the native microsecond `duration` column; do not use that shortcut for acceptance. Native SQL such as `duration > 5000` means greater than5ms and can be used through the existing SQL mode when such a filter is needed. No upstream code patch is part of this migration.
Provisioning from the actual pinned plugin consumers: data source `type: openobserve`, top-level URL/access proxy, `basicAuth: true`, `basicAuthUser` and `secureJsonData.basicAuthPassword`. The declared TypeScript `apiKey` is not read by the backend. Actual jsonData keys include `timestamp_column`, `default_organization`, `default_log_stream`, `default_trace_stream`, `log_message_field`, `trace_id_field`, `span_id_field`, `service_name_field`, `span_name_field` and `status_field`; there are no configurable start/end keys. Set values from measured native schema, not invented aliases.
Trace lookup target uses `queryType: trace_id`, `streamType: traces`, actual stream/organization, both `traceId` and `query` equal to the actual trace ID, `sqlMode: false`, `displayMode: trace`. Optional explicit start/end bounds are microseconds; use Grafana's actual time range. Set a positive `GF_DATAPROXY_RESPONSE_LIMIT` in bytes (default/unset0 disables it). The plugin overrides backend total/search timeouts to210/180s; jsonData.timeout is not proof of a shorter bound. Lab7's native query gateway must enforce its documented transport budget; native engine/resource bounds remain explicit.
Native lab6 parser probes established that search `query.size=1` with SQL `LIMIT 2` returns two rows: a size-field guard is not a hard returned-row cap. Use explicit bounded provisioned SQL and verify the actual Grafana response-byte cap and native engine/resource budgets separately. Do not claim a universal1000-row limit from request validation. Native duplicate JSON keys are rejected422; duplicate or percent-encoded GET parameter names and fractional range bounds need their own native gateway controls and positive cases. The initial21-case receipt does not establish those later guards. Provision the native Prometheus data source HTTP method explicitly to match the gateway, rather than assuming Grafana's default.
Use a dedicated query principal restricted to the isolated lab organization and needed read paths. Never put OpenObserve root/admin credentials into Grafana. If native community roles cannot enforce the required read boundary, enforce exact actual query paths with the existing native gateway and verify allow/deny; do not claim a role restriction that the product does not implement. Limit unsigned loading to the exact checked plugin ID. Preserve standard TLS verification on each declared network hop.
Pinned1.1.2 OSS source forces ordinary POST `/api/default/users` creations to Admin even when viewer/user was requested. Do not use that route for the Grafana principal. The actual nonadmin initializer candidate is POST `/api/{org}/service_accounts` with email/first_name/last_name and a one-time token response; native auth and admin denial must be verified before final provisioning. Initial owner password policy is8..128 Unicode characters with lower/upper/digit ASCII and one other character. Capture issued service tokens privately in the same process; publish only safe shape/status evidence.
Native lab6 verification created two service accounts through that exact route: HTTP200 with code/message/token/user; both list as `service_account`. Both can search and ingest JSON, while both receive403 for admin token rotation. They are nonadmin identities, not native read-only or ingest-only roles. Enforce the query/ingest separation with the existing native HAProxy method/path boundary and closed raw listener; test the actual forbidden requests, not the account label. Never provision the initial owner credential to Collector or Grafana in the final configuration.
## Acceptance gates
1. Real current application emits all three signals; OpenObserve queries return their content and shared trace/span identifiers.
2. Grafana displays metrics/histogram percentiles, structured logs and an actual trace waterfall including API, producer/consumer and worker spans; log/trace navigation resolves the same trace.
3. Provisioned dashboards and alerts use the measured names/units and actual rule engine; high error rate, queue lag, SLO windows and firing/resolved transitions are tested with positive controls.
4. Persistence/restart and storage outage preserve core API behavior with bounded SDK/Collector queues. Old on-disk evidence never becomes new PASS without execution.
5. Lab7 additionally proves updated TLS/mTLS/identity/least-privilege and required native OpenBao lifecycle/rotation acceptance. Cached operator heartbeat evidence does not stand for OpenBao.
6. Preserve initial source/config generation through build, runtime and packaging; exclude caches and verify the exact canonical archive boundary.
No large new layers have been approved. First inspect exact public OCI blobs in existing caches read-only; report missing bytes before new pulls. Model downloads for SII remain separately pending and are not authorized by this migration request.
+47
View File
@@ -0,0 +1,47 @@
# Security cases, written before implementation
Default research track: original README track1, worker compromise. One isolated disposable stack, no unrelated stores.
| Situation / input class | Example | Expected result | Level |
|---|---|---|---|
| Valid transport | correct CA, hostname, unexpired leaf, matching key | application/query succeeds | real TLS integration |
| Empty/foreign trust | no CA / second independent CA | verification error, never timeout counted as denial | TLS integration |
| Wrong name | same endpoint, requested invalid.example | hostname verification error | TLS integration |
| Invalid lifetime | expired leaf, future notBefore, expired CA | verifier rejects | unit + TLS integration |
| Missing/foreign client | API/broker/Collector without cert or foreign CA | TLS rejection; no upstream effect | TLS integration |
| Same-CA wrong identity | worker cert on API ingress; LB on broker | identity rejection, permitted control succeeds | TLS integration |
| Local bypass | container IP:8080 / raw S3 / raw Collector | no non-loopback listener; connection refused | namespace integration |
| OpenBao roles | API own path, worker own path, other path, policy write | allow own; deny other/admin | real OpenBao integration |
| OpenBao lifecycle | renewable token, expired/revoked token, sealed server | renew works; new forbidden reads fail; no plaintext/root fallback | integration |
| Database privilege | worker pipeline vs users/messages/roles | permitted pipeline query; denied user/session/message and DDL | PostgreSQL integration |
| Object privilege | worker staging-read/variant-write vs forbidden prefix/admin | allowed exact prefixes, denied forbidden prefix and anonymous read | S3 integration |
| Queue privilege | API cache-only, separate XADD publisher, worker consumer vs admin/other keys | allowed actual commands; denied cross-role/unrelated/admin operations | Valkey integration |
| Rotation | new S3 secret, new worker leaf, revoke old identity | old new-connection denied, worker resumes queued tasks | real integration / track1 |
| API ACL | outsider attachment/meta/content/link, forged X-User-Id | 404 / Bearer identity preserved | public smoke + student HTTP |
| Login budget | concurrent Basic through two replicas | shared429/Retry-After, bounded KDF resources, successful control | HTTP integration |
| Persistence / failover | restart stores; stop actual serving instance | same session/data survive; second replica serves | public resilience |
| Secret leakage | git/build context/container logs/telemetry | no generated secret values/private material | artifact + runtime scan |
| Hardening | read-only app; all cap-drop, limits, no socket | effective docker inspect matches topology | runtime audit |
Failures: dependency timeout, malformed certificate/key, unavailable/sealed Bao, agent renewal failure, partial bootstrap, revoked client with existing pool, certificate rotation with stale process, S3/DB/broker outage, stopped worker and durable queued task, migration failure, incomplete teardown. Preserve the primary error privately and report its static stage; never count transport timeout as successful security rejection. Already-open TLS connections require explicit drain/reconnect in revocation tests.
## Freshness adapter cases before code
| Situation | Example | Expected result | Level |
|---|---|---|---|
| Exact freshness boundaries | timestamp now, age120s, age120s+1ns | first two valid, last stale | fake-clock unit |
| Malformed/future input | empty, bad date, extra data, now+1ns | explicit invalid/future failure | unit |
| Bounded input |128bytes or129bytes; reader ignores requested limit | never accept oversized input; read requests129bytes at most | unit + real file integration |
| I/O failure | reader returns permission/unavailable | explicit unreadable failure, no raw path/data in error | fake reader unit |
| Later expiry | advance fake time, deliver tick | Run returns ErrStale and stops ticker | fake ticker unit |
| Later read failure | valid first read then failed second | Run returns ErrUnreadable | fake ticker unit |
| Cancellation | cancel before Check or during Run | context error; ticker closed once | unit |
| Invalid factory/timing | missing port, interval0, interval>5s/maxAge | constructor rejects before reading/ticking | unit |
Production adapter never os.Exit or sends signals. Composition owner maps returned error to graceful shutdown. Timestamp format is RFC3339Nano (UTC preferred); native Bao template uses timestamp only inside a successfully read own-secret block. Temporary default max age120s/poll5s gives stale detection approximately within125s plus shutdown grace under normal localFS/scheduling. The reader checks context before/after its syscall and cannot interrupt a hung filesystem; this is not a universal wall-clock bound.
## OpenBao KVv2 response boundary before correction
The native HTTP wrapper returns `{status,data:completeHttpJSON}`. KVv2 secret fields are therefore under `result.data.data.data`; metadata is `result.data.data.metadata`. A200alone or one fewer data level is not a successful secret read.
Cases: correctly nested API and worker payloads accepted; missing nested data, missing required secret, wrong database/cache/S3 role, missing publisher identity for worker, invalid metadata.version and denied HTTP status rejected with fixed safe errors. Tests first reproduce the old flattened reader failure before replacing it.
+3
View File
@@ -0,0 +1,3 @@
import {resolve} from 'node:path';
const workspace=resolve(import.meta.dir,'..'),root=resolve(workspace,'lab5');const results=[];
for(const workers of [1,2,4]){const gate=Bun.spawnSync(['game-running'],{stdout:'pipe',stderr:'pipe'});if(gate.exitCode!==1){console.log(JSON.stringify({benchmarkSkipped:true,gateExit:gate.exitCode,completedProfiles:results.length}));process.exit(0)};console.log(JSON.stringify({gameRunningExit:1,concurrency:workers,cpuLimit:1,memoryLimit:'2GiB',sampling:'2seconds, one run; per-attempt p95 and per-process VmHWM'}));const r=Bun.spawnSync([resolve(root,'scripts/compose.sh'),'run','--rm','--no-deps','--entrypoint','/argon-bench.test','-v',resolve(workspace,'lab7-argon-bench.test')+':/argon-bench.test:ro','-e','KDF_CONCURRENCY='+workers,'worker','-test.run','^$','-test.bench','^BenchmarkArgonLogin$','-test.benchtime=2s','-test.count=1'],{cwd:root,stdout:'pipe',stderr:'pipe'});const out=new TextDecoder().decode(r.stdout);console.log(out);if(r.exitCode!==0){console.error(new TextDecoder().decode(r.stderr));throw new Error('Argon benchmark failed')};results.push({workers,exit:r.exitCode})};console.log(JSON.stringify({allProfilesPassed:true,profiles:results}));
@@ -0,0 +1,53 @@
{
"checkedAt": "2026-11-16T04:36:58.403Z",
"wire": [
{
"phase": "cold",
"path": "/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/grafana-page-history:bg4fowucaheyoa",
"method": "GET",
"status": 404,
"contentType": "application/json",
"bytes": 365
},
{
"phase": "cold",
"path": "/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/grafana-page-history:bg4fowucaheyoa",
"method": "GET",
"status": 404,
"contentType": "application/json",
"bytes": 365
},
{
"phase": "cold",
"path": "/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/",
"method": "POST",
"status": 201,
"contentType": "application/json",
"bytes": 1440
},
{
"phase": "reload",
"path": "/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/grafana-page-history:bg4fowucaheyoa",
"method": "GET",
"status": 200,
"contentType": "application/json",
"bytes": 1440
}
],
"issues": [
{
"phase": "cold",
"type": "error",
"text": "Failed to load resource: the server responded with a status of 404 (Not Found)"
},
{
"phase": "cold",
"type": "error",
"text": "Failed to load resource: the server responded with a status of 404 (Not Found)"
}
],
"source": "actual shipped pageHistorySrv/userStorage delivered sourcemap; GET404 is missing resource, not storage failure",
"normalUIWrite": true,
"readAfterPersist": true,
"unexpectedReloadIssues": 0
}
@@ -0,0 +1,302 @@
import { type Location } from 'history';
import { throttle } from 'lodash';
import { distinctUntilChanged } from 'rxjs';
import * as z from 'zod';
import { type NavModelItem } from '@grafana/data';
import { locationService } from '@grafana/runtime';
import { UserStorage } from '@grafana/runtime/internal';
import { type AppChromeService, getPageTitle } from 'app/core/components/AppChrome/AppChromeService';
import { isUrlRewrite } from 'app/core/navigation/urlRewrite';
import impressionSrv from 'app/core/services/impression_srv';
import { parseJsonWithSchema } from 'app/core/utils/parseJsonWithSchema';
import { isRenderTarget } from 'app/features/dashboard/services/isRenderTarget';
import { classifyPage, recordableSearch } from './classifyPage';
import { hasNothingToResume } from './hasNothingToResume';
import {
clearHistory,
EMPTY_HISTORY,
fitsEntryCap,
type HistorySnapshot,
type HistoryState,
mergeStored,
PAGE_HISTORY_MAX_PER_KIND,
recordTitle,
recordVisit,
toStored,
} from './pageHistoryState';
import { type PageHistoryEntry } from './types';
const STORAGE_SERVICE = 'grafana-page-history';
/** One envelope per user; the user-storage namespace already separates orgs. */
const STORAGE_KEY = 'history';
/** Ordinary URL changes coalesce into one write per window; hiding the tab and `clear()` write at once. */
export const PAGE_HISTORY_PERSIST_MS = 30_000;
/** JS `Date` range; larger values are not instants. */
const MAX_EPOCH_MS = 8.64e15;
/** Persisted row. The page identity is derived from the pathname on load, so a rule change reclassifies old rows. */
const StoredEntrySchema = z.object({
pathname: z
.string()
.startsWith('/')
.refine((pathname) => !pathname.startsWith('//')),
search: z.string().refine((search) => search === '' || search.startsWith('?')),
lastVisited: z.number().int().min(0).max(MAX_EPOCH_MS).optional(),
title: z.string().optional(),
});
/** Everything stored under the key. `clearedAt` is the epoch ms of the last clear, 0 when never cleared. */
const StoredSchema = z.object({
clearedAt: z.number().int().min(0).max(MAX_EPOCH_MS),
entries: z.array(z.unknown()),
});
/**
* Validates the stored copy row by row so one bad or oversized entry drops only itself. Rows that no longer
* classify are dropped. Anything but the envelope loads as empty.
*/
function parseStored(raw: string | null): HistorySnapshot {
const { clearedAt, entries: rows } = parseJsonWithSchema(raw, StoredSchema, { clearedAt: 0, entries: [] });
const entries: PageHistoryEntry[] = [];
for (const row of rows) {
const result = StoredEntrySchema.safeParse(row);
if (!result.success || !fitsEntryCap(result.data)) {
continue;
}
const page = classifyPage(result.data.pathname, result.data.search);
if (page) {
entries.push({ ...result.data, ...page });
}
}
return { clearedAt, entries };
}
function serialize({ clearedAt, entries }: HistoryState): string {
return JSON.stringify({ clearedAt, entries: entries.map(toStored) });
}
/**
* Records the pages the user visits (with their URL state) so the homepage can link back to them.
* One envelope per user and org in `UserStorage`. Every write merges with the stored copy under a version check,
* so tabs and browsers converge; localStorage is used only for signed-out users and is not a fallback for
* failed requests. The merge rules live in `pageHistoryState`; this class wires events and storage to them.
*
* Request policy: ordinary URL changes coalesce into one write at most every `PAGE_HISTORY_PERSIST_MS` per tab;
* hiding the tab and `clear()` write immediately; every `getEntries()` and the startup load each cost one read.
* A write is one read plus one write, plus one more pair per version conflict. A failed write is retried by the
* next change or tab hide, never on a timer. Overlapping operations in one tab serialize on `UserStorage`'s
* lock; a change made while a write is in flight is picked up by the next one. The write on tab hide is a plain
* request, so closing the tab can lose the changes of the current window.
*/
export class PageHistorySrv {
private state = EMPTY_HISTORY;
/** Memory holds a change that storage has not confirmed. */
private dirty = false;
private readonly storage = new UserStorage(STORAGE_SERVICE);
private ready: Promise<void> | undefined;
/**
* Changes made before the stored copy is in, replayed in order once it is. A visit that only refreshes a
* page's row (a menu destination, a rewrite) has to see the stored row, or it finds none and changes nothing.
*/
private pending: Array<() => void> | undefined = [];
/** The menu as it is now, read per visit: items come and go with permissions, plugins and bookmarks. */
private navTree: () => NavModelItem[] = () => [];
private readonly scheduleWrite = throttle(() => this.write(), PAGE_HISTORY_PERSIST_MS, {
leading: false,
trailing: true,
});
/**
* Starts recording. `navTree` is read on every visit to tell menu destinations from pages worth a row. Returns a
* function that stops recording and drops any pending write. Renderer sessions record nothing.
*/
start(chrome: AppChromeService, navTree: () => NavModelItem[]): () => void {
// Image-renderer and report captures load pages as the user; their visits are not the user's.
if (isRenderTarget()) {
return () => {};
}
this.ready = this.load();
this.navTree = navTree;
// `history.listen` never emits the landing page.
this.apply(locationService.getLocation(), false);
const unlisten = locationService
.getHistory()
.listen((location, action) => this.apply(location, action === 'REPLACE' && isUrlRewrite(location.state)));
// Pages set their nav after they render, so the title arrives after the navigation was recorded. Only a nav
// change is a page setting its nav; other chrome updates keep the previous page's nav objects.
const chromeSubscription = chrome.state
.pipe(distinctUntilChanged((a, b) => a.sectionNav === b.sectionNav && a.pageNav === b.pageNav))
.subscribe((state) => this.setTitle(getPageTitle(state)));
const onVisibilityChange = () => {
if (document.visibilityState === 'hidden' && this.dirty) {
void this.writeNow();
}
};
document.addEventListener('visibilitychange', onVisibilityChange);
return () => {
unlisten();
chromeSubscription.unsubscribe();
document.removeEventListener('visibilitychange', onVisibilityChange);
this.pending = undefined;
this.scheduleWrite.cancel();
};
}
/** Newest first, including what other tabs and browsers recorded. Empty until recording has started. */
async getEntries(): Promise<PageHistoryEntry[]> {
if (!this.ready) {
return [];
}
await this.ready;
await this.sync(false);
return [...this.state.entries];
}
/**
* Forgets every recorded page, in every tab and browser, and persists right away. Resolves after the first
* attempt whether or not it reached storage; a failed attempt is retried like any other change.
*/
async clear(): Promise<void> {
if (!this.ready) {
return;
}
await this.ready;
this.state = clearHistory(this.state, Date.now());
this.dirty = true;
await this.writeNow();
}
private async load(): Promise<void> {
// An unreachable store must not seed: it may well hold a history already.
if ((await this.sync(false)) === 'empty') {
await this.seed();
}
const pending = this.pending;
this.pending = undefined;
pending?.forEach((change) => change());
}
/**
* First use for this user and org: carries the newest dashboards over from the recently-viewed impressions.
* They have no visit time, so they sort after every recorded page and are the first to be evicted. A bridge
* for users who had a Recent tab before page history; remove once that is a few releases back.
*/
private async seed(): Promise<void> {
let uids: string[] = [];
try {
uids = await impressionSrv.getDashboardOpened();
} catch (e) {
console.warn('Page history: seed failed', e);
}
const seeded: PageHistoryEntry[] = uids
.slice(0, PAGE_HISTORY_MAX_PER_KIND)
.map((uid) => ({ kind: 'dashboard', uid, pathname: `/d/${uid}`, search: '' }));
this.state = mergeStored(this.state, { clearedAt: 0, entries: seeded });
this.persist();
}
/**
* Merges the stored copy into memory and, with `persist`, stores the result when it differs. `empty`: nothing
* has ever been stored for this user and org. `unreachable`: a request failed and nothing was stored.
*/
private async sync(persist: boolean): Promise<'merged' | 'empty' | 'unreachable'> {
let outcome: 'merged' | 'empty' = 'empty';
try {
await this.storage.updateItem(STORAGE_KEY, (raw) => {
outcome = raw === null ? 'empty' : 'merged';
// Runs again after a version conflict; `mergeStored` is idempotent, so that is safe.
this.state = mergeStored(this.state, parseStored(raw));
const next = serialize(this.state);
return persist && next !== raw ? next : undefined;
});
return outcome;
} catch (e) {
console.warn('Page history: storage unavailable', e);
return 'unreachable';
}
}
/** Hash deliberately ignored. */
private apply(location: Location, isRewrite: boolean): void {
const page = classifyPage(location.pathname, location.search);
if (!page) {
return;
}
// A page with nothing to resume gets no row, but a row it has is refreshed to where the user left it.
const refreshOnly = isRewrite || hasNothingToResume(page, location.search, this.navTree());
const search = recordableSearch(page, location.search);
const at = Date.now();
this.record(() => recordVisit(this.state, page, search, at, refreshOnly));
}
/**
* Stamps the chrome's title onto the row of the page the user is on, if that page has one. The chrome does not
* say which page a nav belongs to and keeps the previous page's nav across a navigation within one route
* (dashboard to dashboard, one app page to another), so a new row stays untitled until its own page sets its
* nav. A nav the departed page sets after the navigation still lands on the new row; the page's own nav
* replaces it once set.
*/
private setTitle(title: string | undefined): void {
if (!title) {
return;
}
const { pathname, search } = locationService.getLocation();
const page = classifyPage(pathname, search);
if (page) {
const at = Date.now();
this.record(() => recordTitle(this.state, page, title, at));
}
}
/**
* Applies `change` to the state, after the stored copy is in. Stamps are taken when the change is made, so a
* replay keeps the order of events; the write it arms waits for the load as every write does.
*/
private record(change: () => HistoryState): void {
if (this.pending) {
this.pending.push(() => this.update(change()));
this.persist();
return;
}
this.update(change());
}
/** Adopts a change made in this tab, if `next` is one: written at the end of the current window. */
private update(next: HistoryState): void {
if (next === this.state) {
return;
}
this.state = next;
this.persist();
}
/** Something changed: written at the end of the current window. */
private persist(): void {
this.dirty = true;
this.scheduleWrite();
}
/** Writes now instead of at the end of the window. */
private writeNow(): Promise<void> {
this.scheduleWrite.cancel();
return this.write();
}
private async write(): Promise<void> {
// Never overwrite the stored copy before it has been merged in.
await this.ready;
// Cleared first so a change made while this write is in flight stays pending.
this.dirty = false;
if ((await this.sync(true)) === 'unreachable') {
this.dirty = true;
}
}
}
export const pageHistorySrv = new PageHistorySrv();
@@ -0,0 +1,18 @@
{
"scope": "actual shipped frontend from the verified Grafana13.3.1 image; public tag source is not substituted",
"imageID": "sha256:1c88285f1dd391a62232c010e6c224846e6a73bdc583b3365be2eba614b7919e",
"reportedCommit": "da3aa3ff574e7dbbf808c66b6daa744defed0441",
"bundle": {"path":"/usr/share/grafana/public/build/18631.ceb2a2734f477243.js","bytes":3030265,"sha256":"b71e20545a118a186841598d30573cb34c7949ce89527e9b4ca8e451ef919458"},
"map": {"path":"/usr/share/grafana/public/build/18631.ceb2a2734f477243.js.map","bytes":15209200,"sha256":"45ffad904b41b1d9901f400215b9efcac88e9a98baa0fb0fb9378407f8a56b8c"},
"deliveredSources": [
{"path":"packages/grafana-runtime/src/utils/userStorage.tsx","file":"history-user-storage-source.txt","sha256":"aee99a03048c1d7e639ad16e80d874508033a18f32c18955914dfc96624d1e28","reader":"fetchResource: status404 returns null; other failures throw; apiRequest sets showErrorAlert:false"},
{"path":"public/app/core/services/pageHistory/pageHistorySrv.ts","file":"history-page-service-source.txt","sha256":"a8970b0388671b359a1721a6d6eb9913a5df4d30251fd40cb37621cfd0f5a2a2","reader":"start->load->sync(false); missing null means empty, then seed; ordinary writes throttled30000ms"}
],
"exactOwnedRoute":"/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/grafana-page-history:bg4fowucaheyoa",
"nativePositive":"history-normal-ui.json",
"rawColdConsole404Count":2,
"normalUIWriteHTTP":201,
"sameKeyReloadGET":200,
"unexpectedReloadErrors":0,
"exception":"Only this proven expected missing-state GET404; no blanket404/403 whitelist and no claim that raw console errors were absent"
}
@@ -0,0 +1,306 @@
import { get, noop } from 'lodash';
import { useRef } from 'react';
import { lastValueFrom } from 'rxjs';
import { usePluginContext, type UserStorage as UserStorageType, store } from '@grafana/data';
import { config } from '../config';
import { type BackendSrvRequest, getBackendSrv } from '../services';
const baseURL = `/apis/userstorage.grafana.app/v0alpha1/namespaces/${config.namespace}/user-storage`;
// Per resourceName (e.g. "plugin-id:user-uid"): the spec, or `null` once a GET returned 404.
// Only touched under the operation lock, so it never has to hold a pending load.
const storageCache = new Map<string, UserStorageSpec | null>();
// Per resourceName: settles once the last queued operation has finished.
const operationLocks = new Map<string, Promise<void>>();
// Each attempt costs one GET and one write; this bounds the cost of a key many tabs fight over.
const WRITE_ATTEMPTS = 3;
/**
* Clears the global storage cache. Used for testing purposes.
* @internal
*/
export function _clearStorageCache() {
if (process.env.NODE_ENV !== 'test') {
throw new Error('clearStorageCache() function can only be called from tests.');
}
storageCache.clear();
operationLocks.clear();
}
interface RequestOptions extends BackendSrvRequest {
// rtk codegen sets this
body?: BackendSrvRequest['data'];
}
type UserStorageSpec = {
data: { [key: string]: string };
};
type UserStorageResource = {
metadata: { resourceVersion: string };
spec: UserStorageSpec;
};
async function apiRequest<T>(requestOptions: RequestOptions) {
try {
const { data: responseData, ...meta } = await lastValueFrom(
getBackendSrv().fetch<T>({
...requestOptions,
url: baseURL + requestOptions.url,
data: requestOptions.body,
showErrorAlert: false,
})
);
return { data: responseData, meta };
} catch (error) {
return { error };
}
}
/**
* A class for interacting with the backend user storage.
* Exposed internally only to avoid misuse (wrong service name).
*
* Two failure policies coexist on purpose. `getItem`, `setItem`, `deleteItem` and `allItems` fall back to
* localStorage when a request fails, so a plugin keeps working. `updateItem` rejects instead: its callers
* merge against the stored copy, and a merge over a copy the server never saw is worse than no write.
*/
export class UserStorage implements UserStorageType {
private service: string;
private resourceName: string;
private userUID: string;
private canUseUserStorage: boolean;
constructor(service: string) {
this.service = service;
this.userUID = config.bootData.user.uid === '' ? config.bootData.user.id.toString() : config.bootData.user.uid;
this.resourceName = `${service}:${this.userUID}`;
this.canUseUserStorage = config.bootData.user.isSignedIn;
}
private localKey(key: string) {
return `${this.resourceName}:${key}`;
}
/** Runs `operation` once every earlier operation on this resourceName has settled, whether it succeeded or threw. */
private runExclusive<T>(operation: () => Promise<T>): Promise<T> {
const previous = operationLocks.get(this.resourceName) ?? Promise.resolve();
const result = previous.then(operation);
const tail = result.then(noop, noop);
operationLocks.set(this.resourceName, tail);
tail.then(() => {
if (operationLocks.get(this.resourceName) === tail) {
operationLocks.delete(this.resourceName);
}
});
return result;
}
/** The stored resource, `null` when none exists yet (404). Throws on any other failure. */
private async fetchResource(): Promise<UserStorageResource | null> {
const response = await apiRequest<UserStorageResource>({ url: `/${this.resourceName}`, method: 'GET' });
if ('error' in response) {
if (get(response.error, 'status') === 404) {
return null;
}
throw response.error;
}
return response.data;
}
private createResource(data: UserStorageSpec['data']) {
return apiRequest<UserStorageResource>({
url: `/`,
method: 'POST',
body: {
metadata: { name: this.resourceName, labels: { user: this.userUID, service: this.service } },
spec: { data },
},
});
}
/** Merge-patch; a `null` value deletes that key. With `metadata.resourceVersion` the server rejects a stale write. */
private patchResource(body: {
metadata?: { resourceVersion: string };
spec: { data: Record<string, string | null> };
}) {
return apiRequest<UserStorageResource>({
headers: { 'Content-Type': 'application/merge-patch+json' },
url: `/${this.resourceName}`,
method: 'PATCH',
body,
});
}
/** Fills the cache on first use. Runs under the lock, so nothing reads the cache mid-load. Returns the load error, if any. */
private async init(): Promise<unknown> {
if (storageCache.has(this.resourceName)) {
return;
}
try {
storageCache.set(this.resourceName, (await this.fetchResource())?.spec ?? null);
} catch (error) {
return error;
}
return;
}
async getItem(key: string): Promise<string | null> {
if (!this.canUseUserStorage) {
return store.get(this.localKey(key)) ?? null;
}
return this.runExclusive(async () => {
await this.init();
const spec = storageCache.get(this.resourceName);
if (!spec) {
// No resource yet, or the load failed: fall back to localStorage
return store.get(this.localKey(key)) ?? null;
}
return spec.data[key] ?? null;
});
}
async setItem(key: string, value: string): Promise<void> {
if (!this.canUseUserStorage) {
store.set(this.localKey(key), value);
return;
}
return this.runExclusive(async () => {
const error = await this.init();
if (error) {
store.set(this.localKey(key), value);
return;
}
const spec = storageCache.get(this.resourceName);
const result = spec
? await this.patchResource({ spec: { data: { [key]: value } } })
: await this.createResource({ [key]: value });
if ('error' in result) {
store.set(this.localKey(key), value);
return;
}
storageCache.set(this.resourceName, { data: { ...spec?.data, [key]: value } });
});
}
/**
* Read-modify-write of one item against what is stored right now. `update` gets the stored value
* (`null` when there is none) and returns the value to store, or `undefined` to store nothing.
* Signed in: fetches the resource fresh, writes with its `metadata.resourceVersion` so the server
* rejects a write over a copy it has not seen, and on that rejection re-reads and re-runs `update`
* (`WRITE_ATTEMPTS` times). Every snapshot it fetches refreshes the cache, so a later `getItem` sees the
* fresh value even when the write fails. Rejects when a request fails; nothing is written to localStorage.
* Signed out: localStorage. There is no cross-tab lock, so two tabs updating at the same instant can drop
* one update; the next update merges from storage again.
*/
async updateItem(key: string, update: (current: string | null) => string | undefined): Promise<void> {
if (!this.canUseUserStorage) {
const next = update(store.get(this.localKey(key)) ?? null);
if (next !== undefined) {
store.set(this.localKey(key), next);
}
return;
}
return this.runExclusive(async () => {
for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt++) {
const resource = await this.fetchResource();
storageCache.set(this.resourceName, resource?.spec ?? null);
const next = update(resource?.spec.data[key] ?? null);
if (next === undefined) {
return;
}
const result = resource
? await this.patchResource({
metadata: { resourceVersion: resource.metadata.resourceVersion },
spec: { data: { [key]: next } },
})
: await this.createResource({ [key]: next });
if ('error' in result) {
// Stale version, or another client created the resource first: re-read and run `update` again.
if (get(result.error, 'status') === 409) {
continue;
}
throw result.error;
}
storageCache.set(this.resourceName, { data: { ...resource?.spec.data, [key]: next } });
return;
}
throw new Error('User storage: conflicting writes');
});
}
async deleteItem(key: string): Promise<void> {
if (!this.canUseUserStorage) {
store.delete(this.localKey(key));
return;
}
return this.runExclusive(async () => {
const error = await this.init();
const spec = storageCache.get(this.resourceName);
if (error || !spec) {
// Nothing to delete server-side (load failed or no resource); clear the localStorage fallback instead
store.delete(this.localKey(key));
return;
}
const result = await this.patchResource({ spec: { data: { [key]: null } } });
if ('error' in result) {
store.delete(this.localKey(key));
return;
}
const { [key]: _, ...data } = spec.data;
storageCache.set(this.resourceName, { data });
});
}
async allItems(): Promise<Record<string, string>> {
if (!this.canUseUserStorage) {
return store.all(`${this.resourceName}:`);
}
return this.runExclusive(async () => {
await this.init();
const spec = storageCache.get(this.resourceName);
return spec ? { ...spec.data } : store.all(`${this.resourceName}:`);
});
}
}
// This is a type alias to avoid breaking changes
export interface PluginUserStorage extends UserStorageType {}
/**
* A hook for interacting with the backend user storage (or local storage if not enabled).
* @returns An scoped object for a plugin and a user with getItem and setItem functions.
* @alpha Experimental
*/
export function usePluginUserStorage(): PluginUserStorage {
const context = usePluginContext();
const ref = useRef<[id: string, PluginUserStorage] | undefined>(undefined);
if (!context) {
throw new Error(`No PluginContext found. The usePluginUserStorage() hook can only be used from a plugin.`);
}
if (!ref.current || ref.current[0] !== context.meta.id) {
ref.current = [context.meta.id, new UserStorage(context.meta.id)];
}
return ref.current[1];
}
/**
* Internal Grafana-core only interface for constructing a UserStorage instance in a
* react component.
*/
export function useUserStorage(service: string): UserStorageType {
const ref = useRef<[service: string, UserStorageType] | undefined>(undefined);
if (!ref.current || ref.current[0] !== service) {
ref.current = [service, new UserStorage(service)];
}
return ref.current[1];
}