RUNBOOK — GatewayQR Municipal
Operator guide for the gateway that lets CYRE POS terminals take Billetera Municipal QR payments.
Written and maintained by the agent; a human validates it on the CYRE server (uscha.config.json, operability).
Repository status: the repo has no remote yet. The workflows in
.github/workflows/(ci.yml,release.yml) are ready for when it is published. Until then the release is built locally with the commands in section 4 and copied to the server by hand.
Contents: 1 Prerequisites · 2 Database · 3 Configuration · 4 Install · 5 Smoke test · 6 CYRE POS rollout · 7 Operations · 8 Upgrade and rollback · 9 Logs and secrets · 10 Dev bench and BootUI
1. Prerequisites
- [ ] Server: Windows Server, JDK 25 (Eclipse Temurin 25 LTS) on the machine, NSSM (the service manager).
- [ ] SQL Server: 2022 is the certified target. 2016 SP1 or later is compatible, not certified (ADR-002): the migrations use only T-SQL of 2016 SP1, but nothing is tested on it and 2016 is out of vendor support.
- [ ] Network, inbound: CYRE POS terminals reach the gateway over the CYRE VPN/MPLS (default port 8080). The POS API has no authentication by design: it must be reachable from the VPN only.
- [ ] Network, outbound: the gateway reaches the municipal API over HTTPS (
vecino.villaallende.gov.ar, sandbox and production URLs in the config). - [ ] Build machine (not necessarily the server): JDK 25, Maven 3.9+, a SQL Server for the integration tests, and
internet access. The console build downloads Node 26 and the npm packages (
frontend-maven-plugin), and Maven downloads its dependencies. Offline build: not supported. Build where there is internet and copy the jar to the server; the server itself needs no internet except the municipal API. - [ ] Admins' VPN address or range (for the cockpit allow-list) and the VPN address of the server interface.
- [ ] SQL Server TLS certificate the JVM trusts. The gateway connects with
encrypt=trueand validates the certificate (trust-server-certificate: false). A default SQL Server install has only a self-signed certificate, and the gateway connects togqrm.db.host(defaultlocalhost), which must match the name in the certificate. Otherwise the first start fails andlogs\gateway.err.logshows... could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption: Error: PKIX path building failed ...(certificate not trusted) orFailed to validate the server name "localhost" ... Name in certificate "..."(name mismatch). The installer (4.2) fails the same way. Before the install:- give SQL Server a certificate whose subject/SAN is this server's name (SQL Server Configuration Manager >
Protocols > Certificate), and make its issuing CA (or the certificate itself) trusted by the JDK: import it into the
JDK truststore (
keytool -importcert -cacerts -alias gqrm-sql -file <cert.cer>, as administrator; repeat after a JDK upgrade, which replacescacerts); - set
gqrm.db.hostto the name in the certificate, notlocalhost(section 3). - Alternative, operator decision:
trust-server-certificate: truekeeps the traffic encrypted but does not authenticate the server, so anyone on the network path can impersonate it and capture the SQL login. Acceptable only when SQL Server runs on this same machine andgqrm.db.hostis a loopback address (127.0.0.1), so the connection never leaves the host. Record the decision (who, when, why) with the install record.
- give SQL Server a certificate whose subject/SAN is this server's name (SQL Server Configuration Manager >
Protocols > Certificate), and make its issuing CA (or the certificate itself) trusted by the JDK: import it into the
JDK truststore (
- [ ] Clock: the server clock is synchronised (Windows Time / NTP,
w32tm /query /status). Charge expiry, the 20 s POS abandonment rule and every audit timestamp depend on it.
2. Database
The gateway never runs as sa and never as db_owner. Use the script db/admin/create-app-login.sql: it creates the
database (when missing) and one dedicated login/user.
Grants, and why:
| Grant | Reason |
|---|---|
db_datareader, db_datawriter |
Everything the gateway does at runtime: read and write its tables, purge wire_log. |
db_ddladmin |
Flyway runs on every start and applies pending migrations (create/alter tables, indexes, constraints, triggers; it also keeps flyway_schema_history). |
| nothing else | No db_owner, no server role, no CONTROL, no other database. |
Decision: one login with db_ddladmin, not two logins. A second "migration" login would have to be supplied to the same
process at every start (Flyway runs inside the gateway), so its password would sit next to the runtime one and buy nothing.
The login was tested to apply all the migrations in the jar with exactly these roles.
Trade-off (CONSTITUTION C7): db_ddladmin can also alter, disable or drop the trigger that keeps attempt_event
append-only. The guarantee therefore holds against the gateway code, not against someone who has this login's password: keep
the password in the vault and the config file restricted (section 3).
Optional hardening for a strict site: after a successful start, ALTER ROLE db_ddladmin DROP MEMBER [<app user>] (the
GQRM_APP_USER chosen below, gqrm_app by default), and add it
back only for the start that applies an upgrade (section 8). Not tested: that the gateway starts without db_ddladmin on
an up-to-date schema (Flyway still validates the schema history on every start). If you use it, make one start right after
dropping the role and keep it only if that start succeeds. The documented default is to keep db_ddladmin.
- [ ] As a SQL Server administrator (Windows authentication), in PowerShell from the repo root. The password is read without echo, checked (16+ characters, no single quote: the script cannot test it without leaving it in the SQL Server plan cache) and passed through an environment variable of that session only, never on a command line:
$env:GQRM_DB_NAME = 'GatewayQRMunic'; $env:GQRM_APP_USER = 'gqrm_app'
$s = Read-Host -AsSecureString 'Password for the new login (16+ chars, no single quote)'
try {
$env:GQRM_APP_PASSWORD = [System.Net.NetworkCredential]::new('', $s).Password
if ($env:GQRM_APP_PASSWORD.Length -lt 16 -or $env:GQRM_APP_PASSWORD.Contains("'")) { throw 'Refused: the password needs 16+ characters and no single quote.' }
sqlcmd -S localhost -E -C -b -i db\admin\create-app-login.sql
} finally { Remove-Item Env:GQRM_APP_PASSWORD -ErrorAction SilentlyContinue }
-
[ ] Run the script only through the block above: the block checks the password's length and the single quote; the script checks neither (a quote would end its
N'...'literal). The script runs only throughsqlcmd(or SSMS in SQLCMD mode; otherwise it refuses and changes nothing). It refuses a login that issysadminorsecurityadmin, owns the database or is adb_ownermember.CHECK_POLICY = ONapplies the Windows password policy. -
[ ] Keep the database collation case-insensitive (the SQL Server default): merchant codes are unique under the collation.
- [ ] Store the password in the company password vault. Re-running the script resets the login's password.
- [ ] Back-ups: schedule full + log (or full + differential) back-ups of the database. The attempt and event tables are the reconciliation record; C7: events are append-only (a trigger refuses UPDATE and DELETE). Every restore of this database, for any reason, follows section 8.2 (it re-seeds the attempt numbering: a restored database would otherwise hand out attempt numbers the POS and the Municipality have already seen).
3. Configuration
- [ ] Create and lock the install folder BEFORE any secret is written.
C:\GatewayQRMunic\withconfig\andlogs\inside; the jar reads./config/relative to its working directory, so the service's working directory is the install folder. A folder created underC:\inheritsC:\'s permissions (local users can read it, and create, change and delete files in it), so any local user could readconfig\application-prod.yml(database password, master key) or plant aconfig\application.yml/application.ymlthat Spring Boot also loads (for example another municipal URL, which would receive the merchant API keys). Locking the folder after creating it is not enough: in between, a local user can open it with delete or change-permission rights, and that open handle survives the lock (later the folder could be renamed and replaced while the service is stopped, and the service would run a planted jar with access to the secrets). So the block below creates the folder already locked, in one call, with SIDs (account names are localised on a Spanish Windows:S-1-5-32-544is Administrators,S-1-5-18is SYSTEM): owner Administrators, full control for those two only, nothing inherited fromC:\. Only those two can enter the folder until the service exists; section 4.3 then adds the service, read-only (and Modify onlogs\only). The service cannot be granted now:sc.exe showsidalready prints its SID, buticaclsrefuses a SID of a service that is not installed ("No mapping between account names and security IDs was done"). Why notC:\Program Files\GatewayQRMunic: there only administrators can create folders, so nobody could create the folder first or hold it open; but it inherits read access forUsers, so it would need the same lock, and every path of this runbook, the NSSM settings and the checks would change. Creating the folder with its permissions already set closes the same window, so the install folder staysC:\GatewayQRMunic. Run it in an elevated Windows PowerShell 5.1 (powershell.exe, Run as administrator): the block uses the .NET Framework overload[IO.Directory]::CreateDirectory(path, DirectorySecurity), which PowerShell 7 does not have. First set$template(its first line) to the template in the release or repo folder:
& { # one block: the first failure stops everything below it (paste it whole, including the closing brace)
$ErrorActionPreference = 'Stop'
$template = '<release or repo folder>\config\application-prod.example.yml' # SET THIS PATH FIRST
$root = 'C:\GatewayQRMunic'; $owner = 'S-1-5-32-544'; $full = 'S-1-5-32-544', 'S-1-5-18' # Administrators, SYSTEM
if ($PSVersionTable.PSEdition -ne 'Desktop') { throw 'Run this in Windows PowerShell 5.1 (powershell.exe), not PowerShell 7. Nothing was created.' }
if (-not (Test-Path -LiteralPath $template -PathType Leaf)) { throw "Template not found: $template. Set `$template and paste again. Nothing was created." }
if (Test-Path -LiteralPath $root) { throw "$root already exists. A fresh install needs a folder created now: any local user can create one under C:\ in advance. STOP and investigate; never reuse a folder you did not create." }
# create the folder ALREADY locked: owner Administrators, full control for Administrators and SYSTEM only (inherited by
# everything below it), protected (nothing inherited from C:\)
$sec = New-Object System.Security.AccessControl.DirectorySecurity
$sec.SetOwner([Security.Principal.SecurityIdentifier]$owner)
$sec.SetAccessRuleProtection($true, $false)
foreach ($sid in $full) { $sec.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule([Security.Principal.SecurityIdentifier]$sid, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow'))) }
[void][IO.Directory]::CreateDirectory($root, $sec)
# CreateDirectory also returns quietly when someone created the folder after the check above: verify what is there now
if ((Get-Item -LiteralPath $root -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "$root is a link, not a folder: STOP, write no secret, investigate." }
$acl = Get-Acl -LiteralPath $root; $rules = @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]))
if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $owner) { icacls $root; throw "$root is not owned by Administrators: someone else created it. STOP, write no secret, investigate." }
$odd = $rules | Where-Object { $_.IsInherited -or $_.AccessControlType -ne 'Allow' -or $_.FileSystemRights -ne 'FullControl' -or $_.InheritanceFlags -ne 'ContainerInherit, ObjectInherit' -or $_.PropagationFlags -ne 'None' -or $full -notcontains $_.IdentityReference.Value }
if (-not $acl.AreAccessRulesProtected -or $odd -or $rules.Count -ne $full.Count -or @($rules | ForEach-Object { $_.IdentityReference.Value } | Sort-Object -Unique).Count -ne $full.Count) { icacls $root; throw "$root has other permissions than Administrators and SYSTEM: STOP, write no secret, investigate." }
if (Get-ChildItem -LiteralPath $root -Force) { throw "$root is not empty: STOP, write no secret, investigate." }
New-Item -ItemType Directory -Path "$root\config", "$root\logs" | Out-Null # created inside the locked folder: they inherit its two entries
# COPY (never move: a moved file keeps its old permissions); the copy inherits the locked folder's permissions
Copy-Item -LiteralPath $template -Destination "$root\config\application-prod.yml"
icacls $root /setowner "*$owner" /T
if ($LASTEXITCODE) { throw 'icacls /setowner failed: STOP, write no secret.' }
$notOwned = @(Get-ChildItem -LiteralPath $root -Recurse -Force) | Where-Object { (Get-Acl -LiteralPath $_.FullName).GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $owner }
if ($notOwned) { throw "Not owned by Administrators: $($notOwned.FullName -join ', '). STOP, write no secret." }
notepad "$root\config\application-prod.yml"
}
If the block stops: it stops on the PowerShell edition, the template path or an existing folder before creating
anything: fix the cause and paste it again. An error from CreateDirectory itself ("This security ID may not be
assigned as the owner of this object") also created nothing: the shell is probably not elevated. If it stops on "not
owned by Administrators: someone else created it", "a link", "other permissions" or "not empty", the folder was there
before this block created it: STOP and investigate, do not delete it and retry. If it stops on a later step (after
those checks: New-Item, the copy, icacls /setowner, the final owner check), the folder is the one this block
created: when no secret has been written into it yet, remove it in the elevated shell
(Remove-Item -LiteralPath C:\GatewayQRMunic -Recurse -Force) and paste the block again. Never reuse a folder you did
not create with this block, and never fill in a file of a run that stopped.
Fill in the file with the settings below, then run the check at the end of this section.
- [ ] Database: gqrm.db.host (the name in the SQL Server certificate, see the TLS prerequisite in section 1), port,
name, and gqrm.db.user / gqrm.db.password (the dedicated login) in this file. Keep
trust-server-certificate: false; true only as the recorded loopback-only decision of section 1. (The gateway also
reads the environment variables GQRM_DB_USER / GQRM_DB_PASSWORD, but do not use them for the service: see 4.3.)
- [ ] Master key gqrm.security.master-key (in this file): Base64 of 32 random bytes. The gateway
refuses to start without it and encrypts every merchant API key with it (AES-256-GCM, C2). Generate it once, in
PowerShell (cryptographic generator):
$b = New-Object byte[] 32; [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($b); [Convert]::ToBase64String($b)
(or openssl rand -base64 32). Store a copy in the company vault, separate from the database back-ups.
If the key is lost, every stored merchant API key is unrecoverable: the only remedy is to enter each key again
through the cockpit. There is no tool to re-encrypt: to change the key, stop the service, set the new key, start, and
rotate every merchant's key (payments of a merchant fail until its key is rotated, so plan it as an outage window).
- [ ] Bind address: server.address = the VPN interface address of this server. Left out of the file, the jar default
127.0.0.1 applies: the gateway starts but listens on the loopback only, so no POS can reach it. The prod profile
refuses to start on an address that binds every interface (0.0.0.0, ::) (ProdBindAddressGuard). Default
port server.port: 8080.
- [ ] Cockpit allow-list: gqrm.admin.allowed-addresses = 127.0.0.1,::1,<admins' VPN address or CIDR>. It is mandatory:
the guard also refuses to start when the server listens on the VPN but the list names only this machine. Any other
source gets 403 on /admin. The POS API (/api) is not restricted by it. Do not put a reverse proxy on this
machine (every request would look local; the gateway reads no X-Forwarded-For).
- [ ] HTTPS: server.servlet.session.cookie.secure: true only if the cockpit is served over HTTPS; otherwise leave false
or the login never sticks.
- [ ] Municipal URLs: muni.sandbox-base-url and muni.production-base-url (preset in the template). An environment with
no URL can never be called.
- [ ] Environment per merchant (C6): each merchant is SANDBOX or PRODUCTION, set in the cockpit. A sandbox key is
never sent to the production URL or the reverse; the environment is checked before every call. Changing a merchant's
environment needs the API key of the new environment in the same request and is refused while it has charges in
flight. Start every new merchant in SANDBOX; move it to PRODUCTION only with the production key from the Municipality.
- [ ] Timing (muni.*, pos.*): leave the defaults unless agreed (charge TTL 120 s, poll every 5 s, grace 10 s, POS
abandon 20 s, stuck after 12 refusals then every 300 s). The gateway refuses to start when the stuck interval is not
greater than TTL + grace. The cockpit shows them read-only under "Tiempos". Raising the TTL, the grace or
muni.read-timeout-millis means raising the POS TIMEOUT_RX too (section 6, timing rule).
- [ ] Check the folder and the secrets file (elevated). It stops on any file that is not expected, on any owner other
than Administrators or SYSTEM and on any permission entry other than Administrators and SYSTEM, on every item
including the secrets file itself:
& {
$ErrorActionPreference = 'Stop'
$root = 'C:\GatewayQRMunic'; $allowed = 'S-1-5-32-544', 'S-1-5-18'; $expected = 'config', 'logs', 'config\application-prod.yml'
$items = @(Get-Item -LiteralPath $root -Force) + @(Get-ChildItem -LiteralPath $root -Recurse -Force)
$extra = $items | ForEach-Object { $_.FullName.Substring($root.Length).TrimStart('\') } | Where-Object { $_ -and $expected -notcontains $_ }
if ($extra) { throw "Unexpected files: $($extra -join ', '). STOP and investigate." }
$owners = foreach ($i in $items) { $o = (Get-Acl -LiteralPath $i.FullName).GetOwner([Security.Principal.SecurityIdentifier]).Value; if ($allowed -notcontains $o) { '{0}: {1}' -f $i.FullName, $o } }
if ($owners) { throw "Unexpected owners: $($owners -join '; '). If it is your own administrator account (a file saved from an elevated editor), run icacls <that path> /setowner *S-1-5-32-544 and run this check again; any other owner: STOP and investigate." }
$bad = foreach ($i in $items) { (Get-Acl -LiteralPath $i.FullName).GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) | Where-Object { $allowed -notcontains $_.IdentityReference.Value } | ForEach-Object { '{0}: {1}' -f $i.FullName, $_.IdentityReference } }
if ($bad) { throw "Unexpected permission entries: $($bad -join '; '). STOP." }
icacls "$root\config\application-prod.yml"
}
The last line must list only NT AUTHORITY\SYSTEM and BUILTIN\Administrators (Administradores): no Users /
Usuarios, no Authenticated Users.
- [ ] Keep the folder restricted: only Administrators, SYSTEM and (from section 4.3) the service account may read the
install folder. Never loosen it, and never put another application*.yml in the install folder or under config\.
From now on every step that reads or writes the install folder (copying the jar in 4.1, the installer in 4.2, any later
edit of the config) runs in an elevated shell.
4. Install
4.1 Build the release (on the build machine)
Needs a SQL Server with an empty GatewayQRMunic_IT database and the variables GQRM_DB_USER / GQRM_DB_PASSWORD
(the integration tests wipe that database only; the guard refuses any name that does not end in _IT). Never point them at
the production database.
- [ ] First set the release version
X.Y.Zin the poms (a release is never-SNAPSHOT) and commit it. The build below must run on that commit, so the jar isgatewayqrmunic-X.Y.Z.jar, and the tagvX.Y.Zgoes on the same commit.
mvn clean -DskipITs=false verify
Never add -Pbootui (ADR-002). Then check the jar has no development-only code. Expect no output:
jar tf gateway\target\gatewayqrmunic-<version>.jar | Select-String -Pattern 'bootui|actuator|opentelemetry'
jar tf gateway/target/gatewayqrmunic-<version>.jar | grep -iE 'bootui|actuator|opentelemetry'
- [ ] Any line printed = stop: that is a development build. Rebuild with
mvn cleanand no-Pbootui. - [ ] Tag the version commit
vX.Y.Z(release.ymlbuilds only tags of that form and refuses a-SNAPSHOTversion or a tag that differs from the pom version). The development jar is namedgatewayqrmunic-<version>-bootui-DEV-ONLY.jar: never deploy it (theprodprofile refuses to start it anyway). - [ ] Copy (never move: a moved file keeps its old permissions)
gateway/target/gatewayqrmunic-<version>.jartoC:\GatewayQRMunic\gatewayqrmunic.jar, in an elevated shell (section 3). Keep the migration scripts (gateway/src/main/resources/db/migration/) with the release record; they are inside the jar.
4.2 First administrator (installer mode, C8)
There is no default user. Create the first admin once, from the install folder, in a terminal (it never runs a web server,
poller or purge, so it is safe next to a running gateway; on a fresh database it also creates the schema). Elevated
PowerShell 5.1+ (Run as administrator), every time it runs, including the lost-admin path of 7.5: config\ is readable only
by Administrators, SYSTEM and the service (section 3), and without elevation the installer cannot read its configuration:
cd C:\GatewayQRMunic
$s = Read-Host -AsSecureString; $env:GQRM_FIRST_ADMIN_SECRET = [System.Net.NetworkCredential]::new('', $s).Password; java -jar gatewayqrmunic.jar --spring.profiles.active=prod --gqrm.admin.bootstrap.username=first.admin; Remove-Item Env:GQRM_FIRST_ADMIN_SECRET
Without the variable it asks for the password at the terminal (not echoed). Never type the password as a literal on a command
line and never pass it as --gqrm.admin.bootstrap.password (refused). Rules: username 3 to 50 characters of letters,
digits, ., _, -; password at least 12 characters (at most 72 bytes).
- [ ] It prints "The administrator '...' was created" and ends. It refuses while an enabled ADMIN exists, and refuses when the schema is older than the installer (use the installer of the same version as the running gateway).
- [ ] The password goes in the vault. Further users are created in the cockpit (section 7.5).
4.3 Windows service with NSSM
The service runs as the virtual service account NT SERVICE\GatewayQRMunic: Windows manages it, it has no password
(nothing to type, store or rotate) and it is not an administrator. As administrator, in PowerShell:
nssm install GatewayQRMunic "C:\Program Files\Eclipse Adoptium\jdk-25\bin\java.exe"
nssm set GatewayQRMunic AppParameters "-XX:-UseBASE64Intrinsics -jar gatewayqrmunic.jar --spring.profiles.active=prod"
nssm set GatewayQRMunic AppDirectory C:\GatewayQRMunic
nssm set GatewayQRMunic DisplayName "GatewayQR Municipal"
nssm set GatewayQRMunic Start SERVICE_AUTO_START
nssm set GatewayQRMunic AppStdout C:\GatewayQRMunic\logs\gateway.out.log
nssm set GatewayQRMunic AppStderr C:\GatewayQRMunic\logs\gateway.err.log
nssm set GatewayQRMunic AppRotateFiles 1
nssm set GatewayQRMunic AppRotateOnline 1
nssm set GatewayQRMunic AppRotateBytes 10485760
nssm set GatewayQRMunic AppStopMethodConsole 45000
nssm set GatewayQRMunic AppExit Default Restart
nssm set GatewayQRMunic AppRestartDelay 10000
# the virtual account: a service SID, then the account itself (no password)
sc.exe sidtype GatewayQRMunic unrestricted
sc.exe config GatewayQRMunic obj= "NT SERVICE\GatewayQRMunic"
-XX:-UseBASE64Intrinsics turns off the JDK's Base64 intrinsics, including the decoder affected by CVE-2026-114938
("Java4Shell", RISKS R-10). It costs nothing measurable here and is safe on any CPU. Keep it until the JDK on the
server has the fix for that CVE. A service installed before this flag was added is updated separately: see
"Existing service" at the end of this section (not part of a fresh install).
Then, in the same elevated shell, check the service account and give the service (S-1-5-80-..., now installed, so
icacls accepts it) read access to the install folder locked in section 3, and Modify on logs\ only (NSSM writes the log
files as the service account). Nothing else changes: the folder stays without inherited permissions, owned by
Administrators:
& { # one block: the first failure stops everything below it, including the start (paste it whole)
$ErrorActionPreference = 'Stop'
# the account from WMI, not from sc.exe qc (its labels are translated on a Spanish Windows); -ne ignores letter case
$account = (Get-CimInstance Win32_Service -Filter "Name='GatewayQRMunic'").StartName
if ($account -ne 'NT SERVICE\GatewayQRMunic') { "Service account: '$account'"; throw 'The service does not run as NT SERVICE\GatewayQRMunic (it would run as LocalSystem): STOP, repeat sc.exe config.' }
$svc = [regex]::Match((sc.exe showsid GatewayQRMunic) -join ' ', 'S-1-5-80(-\d+){5}').Value
if (-not $svc) { throw 'No service SID from sc.exe showsid: STOP.' }
icacls C:\GatewayQRMunic /grant "*${svc}:(OI)(CI)RX"
if ($LASTEXITCODE) { throw 'icacls failed: STOP.' }
icacls C:\GatewayQRMunic\logs /grant "*${svc}:(OI)(CI)M"
if ($LASTEXITCODE) { throw 'icacls failed: STOP.' }
$root = 'C:\GatewayQRMunic'; $allowed = 'S-1-5-32-544', 'S-1-5-18', $svc; $expected = 'config', 'logs', 'config\application-prod.yml', 'gatewayqrmunic.jar'
$items = @(Get-Item -LiteralPath $root -Force) + @(Get-ChildItem -LiteralPath $root -Recurse -Force)
# log files of an earlier failed start are expected; their permissions are still checked below
$extra = $items | ForEach-Object { $_.FullName.Substring($root.Length).TrimStart('\') } | Where-Object { $_ -and $expected -notcontains $_ -and $_ -notlike 'logs\*' }
if ($extra) { throw "Unexpected files: $($extra -join ', '). STOP and investigate." }
# owner: Administrators or SYSTEM; files under logs\ may also be owned by the service (NSSM creates them as the service)
$owners = foreach ($i in $items) { $o = (Get-Acl -LiteralPath $i.FullName).GetOwner([Security.Principal.SecurityIdentifier]).Value; $ok = 'S-1-5-32-544', 'S-1-5-18'; if ($i.FullName -like "$root\logs\*") { $ok += $svc }; if ($ok -notcontains $o) { '{0}: {1}' -f $i.FullName, $o } }
if ($owners) { throw "Unexpected owners: $($owners -join '; '). If it is your own administrator account (a file saved or copied from an elevated shell), run icacls <that path> /setowner *S-1-5-32-544 and paste this block again; any other owner: STOP and investigate." }
$bad = foreach ($i in $items) { (Get-Acl -LiteralPath $i.FullName).GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) | Where-Object { $allowed -notcontains $_.IdentityReference.Value } | ForEach-Object { '{0}: {1}' -f $i.FullName, $_.IdentityReference } }
if ($bad) { throw "Unexpected permission entries: $($bad -join '; '). STOP." }
icacls C:\GatewayQRMunic\config\application-prod.yml
nssm start GatewayQRMunic
}
- [ ]
(Get-CimInstance Win32_Service -Filter "Name='GatewayQRMunic'").StartNameshowsNT SERVICE\GatewayQRMunic(any letter case; the block refuses otherwise). Do not check it by readingsc.exe qc: its labels are translated on a Spanish Windows (NOMBRE_INICIO_SERVICIOinstead ofSERVICE_START_NAME). If it showsLocalSystem, the service would run silently as SYSTEM: repeatsc.exe config. - [ ]
nssm get GatewayQRMunic AppParametersstarts with-XX:-UseBASE64Intrinsics. - [ ]
icacls C:\GatewayQRMunic\config\application-prod.ymllists onlyBUILTIN\Administrators(Administradores),NT AUTHORITY\SYSTEMandNT SERVICE\GatewayQRMunic(read): noUsers/Usuarios, noAuthenticated Users. - [ ]
nssm.exesits in a folder the service account can read and execute, such asC:\Program Files\nssm\(NSSM is the service process and runs as the virtual account), never under a user profile (C:\Users\...\Downloads): the service would not start. The same for the JDK (C:\Program Files\...). - [ ] If the start fails with error 1069 ("The service did not start due to a logon failure"), a Group Policy limits
"Log on as a service": it must include
NT SERVICE\ALL SERVICES(orNT SERVICE\GatewayQRMunic). Ask the domain administrator; do not switch the service to LocalSystem. AppDirectorymust be the install folder (Spring reads./config/application-prod.yml). Adjust the JDK path to the installed folder.AppStopMethodConsole 45000gives the JVM time for its 30 s graceful shutdown (in-flight requests finish).- Control:
nssm status|start|stop|restart GatewayQRMunic; edit withnssm edit GatewayQRMunic; remove withnssm remove GatewayQRMunic confirm. - Secrets live only in
config\application-prod.yml(restricted in section 3). Do not pass the database password or the master key through NSSMAppEnvironmentExtra: NSSM keeps it in the registry underHKLM\SYSTEM\CurrentControlSet\Services\GatewayQRMunic\Parameters, which local users can read. Machine-wide environment variables are readable by every local user too. Check:nssm get GatewayQRMunic AppEnvironmentExtraprints no secret.
Existing service (installed before the -XX:-UseBASE64Intrinsics flag). Skip this on a fresh install: the install
block above already sets the flag. Off-hours, with every POS idle and no cashier mid-payment (as in section 8.1), as
administrator:
- Read the current parameters and keep the output:
powershell
nssm get GatewayQRMunic AppParameters
- Set them again as
-XX:-UseBASE64Intrinsicsfollowed by the line from step 1, unchanged. With the standard line from the install block that is:
powershell
nssm set GatewayQRMunic AppParameters "-XX:-UseBASE64Intrinsics -jar gatewayqrmunic.jar --spring.profiles.active=prod"
- Restart, then check the JVM that the service started (NSSM is the service process; the JVM is its child):
powershell
nssm restart GatewayQRMunic
$svcPid = (Get-CimInstance Win32_Service -Filter "Name='GatewayQRMunic'").ProcessId
(Get-CimInstance Win32_Process -Filter "ParentProcessId=$svcPid").CommandLine
The command line must contain -XX:-UseBASE64Intrinsics. An empty result means the JVM did not stay up: read
logs\gateway.err.log.
- Watch
logs\gateway.out.logfor "Started" and run the smoke test (section 5).
4.4 Flyway migrations
- On every start the gateway applies the pending migrations (all the migrations inside the jar) to the database it is pointed at. A fresh database gets the whole schema.
- Forward-only: there is no undo. Rolling back means restoring a back-up (section 8). Applied migrations are never edited
(Flyway would refuse to start on a checksum mismatch). Flyway
cleanis disabled in production. - If a migration fails, the service does not start, and NSSM restarts it every 10 s (
AppExit Restart): firstnssm stop GatewayQRMunic, then readlogs\gateway.err.logand fix the cause (usually permissions: the login needsdb_ddladmin). If the migration was partly applied, restore with the procedure of section 8.2 (it re-seeds the attempt numbering), then start again. - The installer (4.2) never migrates a live database: it only migrates a fresh one.
5. Smoke test (after every install and upgrade)
Use a SANDBOX merchant with the sandbox key the Municipality gave you; never test with a production key. GW is
http://<server.address>:8080.
- [ ] Cockpit login: open
GW/admin/from an allowed address, log in as the admin. From a non-allowed address you must get 403. - [ ] Merchant and key: "Comercios" > "Nuevo comercio": "Código de comercio"
SMOKE-SANDBOX, CUIT (11 digits), "Ambiente"Sandbox, "Clave de API" = the sandbox key. Add a branch ("Nueva sucursal", "Número de sucursal"1). The key is shown once and never again. - [ ] POS contract against the sandbox (PowerShell on the server or an admin PC; the real POS sends the same JSON).
The 20 s rule: the gateway cancels a charge the POS has not asked about for 20 s (
pos.abandon-after-seconds), so the query loop starts in the same line astrxpago, before you pay, and the cancel of step 4 goes within 20 s of itstrxpago.
$GW = 'http://<server.address>:8080'
# 1) allocate an attempt: id, pos 1, sucursal 1, comercio SMOKE-SANDBOX, mediodepago
$a = Invoke-RestMethod -Method Post -Uri "$GW/api/trxid" -ContentType 'application/json' -Body '{"pos":1,"sucursal":1,"comercio":"SMOKE-SANDBOX"}'; $a
# 2) create the municipal charge (estado PAGO_ENVIADO + qrdata, the QR text) AND start polling every 2 s like the POS
# (a failed query is printed and the loop goes on; it always ends after 180 s, more than TTL 120 s + grace 10 s)
$p = Invoke-RestMethod -Method Post -Uri "$GW/api/trxpago" -ContentType 'application/json' -Body ('{"id":' + $a.id + ',"totalitem":100.00,"totalcashback":0,"nropv":"1","nroticketfiscal":"1"}'); $poll = Start-Job -ArgumentList $GW, $a.id -ScriptBlock { param($gw, $id) $end = (Get-Date).AddSeconds(180); $estado = 'PAGO_ENVIADO'; do { try { $r = Invoke-RestMethod "$gw/api/trxes/$id" -TimeoutSec 10 -ErrorAction Stop; $estado = $r.estado; '{0:HH:mm:ss} {1} {2}' -f (Get-Date), $r.estado, $r.mensajevarios } catch { '{0:HH:mm:ss} query failed: {1}' -f (Get-Date), $_.Exception.Message }; if ($estado -eq 'PAGO_ENVIADO') { Start-Sleep 2 } } while ($estado -eq 'PAGO_ENVIADO' -and (Get-Date) -lt $end); if ($estado -eq 'PAGO_ENVIADO') { 'Deadline reached, still PAGO_ENVIADO: check the attempt in the cockpit.' } }; $p.estado; $p.qrdata
# 3) pay the QR with the municipality's sandbox payer tool; this waits for the loop: PAGO_ENVIADO while pending, PAGO_APROBADO when paid
Receive-Job $poll -Wait -AutoRemoveJob
# 4) cancel a second, unpaid attempt within 20 s of its trxpago: AUTORIZACION_DE_ANULACION_APROBADA
$b = Invoke-RestMethod -Method Post -Uri "$GW/api/trxid" -ContentType 'application/json' -Body '{"pos":1,"sucursal":1,"comercio":"SMOKE-SANDBOX"}'
Invoke-RestMethod -Method Post -Uri "$GW/api/trxpago" -ContentType 'application/json' -Body ('{"id":' + $b.id + ',"totalitem":100.00,"totalcashback":0,"nropv":"1","nroticketfiscal":"1"}') | Out-Null; Invoke-RestMethod -Method Post -Uri "$GW/api/trxanulacion" -ContentType 'application/json' -Body ('{"id":' + $b.id + ',"trxidoriginal":' + $b.id + ',"nropv":"1","nroticketfiscal":"1"}')
(curl.exe works too: curl.exe -s -X POST "$GW/api/trxid" -H "Content-Type: application/json" --data-binary '@body.json'
with the same JSON in a file; the query loop and the 20 s rule are the same.)
- [ ] Cockpit screens: "Intentos" lists both attempts (filters: date, branch, POS, status) and the detail shows the event timeline. "Alertas" is empty (no PAID_UNCONFIRMED or other alert from a clean test).
- [ ] Unknown branch:
trxidfor acomercioorsucursalthat does not exist answers 404 "Sucursal no configurada". - [ ] Deactivate the smoke merchant ("Comercios", state change asks for your password) or keep it in SANDBOX. Never leave a test merchant in PRODUCTION.
- [ ] Password-manager check at go-live (manual, in the browser the admins use, with its password manager on): the save bubble must never show the merchant API key or another user's password with a username. Check on: merchant edit, API-key rotation, user creation, password reset. A bubble offering the key, or a username that is not the admin's own login, is a defect: report it, do not go live.
6. CYRE POS rollout checklist (RISKS R-08)
Every POS that enables this method needs the settings below. A POS left at defaults abandons payable charges.
POS profile keys are the pro_PAGOQR_* constants of the CYRE POS (pos_prof.h).
- [ ] Key 543,
pro_PAGOQR_CANCELENABLED= 1 (or 2: the profile comment says it also includes "Cancelar Pago"; this POS build treats any non-zero value the same while waiting). Default 0: Esc does nothing while the QR is waiting, although the QR screen still says "Si no puede pagar presione Esc"; the cashier can then only wait for the time limit below. The cashier table assumes 543 = 1. - [ ] Key 496,
pro_PAGOQR_TIMEOUT_RX: at least 210 (ADR-003 floor); 240 recommended. The POS waits(TIMEOUT_RX / 3) x 2seconds (integer seconds, counted from thetrxpagoanswer) before it asks the cashier "No se pudo completar PAGO QR / Reintenta via Consulta del PAGO?". Timing rule, with headroom:(TIMEOUT_RX / 3) x 2 >= charge TTL + grace + poll tick + 2 x read timeout + POS query cadence(muni.charge-ttl-seconds120,muni.final-query-grace-seconds10,gqrm.poller.tick-millis1 s,muni.read-timeout-millis5 s, key 564 + 3.4 s, see key 564 below), or the simpler fixed margin(TIMEOUT_RX / 3) x 2 >= TTL + grace + 30. With the defaults: 120 + 10 + 1 + 10 + 5.4 = 146.4 s (TIMEOUT_RX 222, since the POS divides in whole seconds); the fixed margin gives 160 s (TIMEOUT_RX 240, which covers both). At the 210 floor (140 s) the charge lifetime plus grace (130 s) is still covered, but a payment in the last seconds of the QR can reach the POS after its limit: the POS then asks "Reintenta via Consulta del PAGO?" and OK (again each time it asks) recovers the payment. If the TTL, the grace or the read timeout is raised, recompute. - [ ] Key 497,
pro_PAGOQR_TIMEOUT_GETID: 10, keep it at 10 (seconds the POS waits for atrxidortrxesanswer; thetrxpagowait is capped in the build, see change 5 below). Key 498,pro_PAGOQR_TIMEOUT_CONN: 5. - [ ] Key 564,
pro_PAGOQR_POLL_SEGUNDOS: 2 (the default; 1 is also safe). Rule: key 564 at 1 or 2, key 497 at 10, key 498 at 5. Key 564 is the pause between two queries (theVerificandolines of the POS log). Each query cycle also costs about 3.4 s of connect, answer, idle read and close, so queries reach the gateway aboutkey 564 + 3.4s apart. The 3.4 s was measured on the DOSBox-X bench (5.4 s observed with 564 = 2, 6.4 s with 564 = 3); measure it again on the first real POS. 20 s budget: the gateway cancels a pending charge when it has received no query forpos.abandon-after-seconds(20). It checks on its 5 s municipal poll and a 1 s poller pass, so the cut falls between 20 and about 26 s. Recompute if that setting changes. Gap between two queries the gateway does receive, by case:- Answer lost (the gateway got the query):
key 497 + 1 + key 564, computed 13 s with 564 = 2. - Request lost after a successful connect: one normal cycle plus one lost cycle,
2 x key 564 + key 497 + 4.4, computed 18.4 s with 564 = 2 and 20.4 s with 564 = 3 (the lost cycle alone was observed at 14.2 s with 564 = 3, a request lost behind the proxy). This case sets the rule above. - Connect fails: one normal cycle, plus the failed connect, plus
key 564, plus the next query's own connect. Key 498 (the connect timeout) did not bound the connect time on the DOSBox-X bench: failed connects to the gateway port took 7 to 11 s while the gateway was down (seen ontrxidandtrxpago, not yet on a query), connects to another service took up to 17 s, and a successful connect to a gateway that was still starting took 6 s. With 564 = 2 and an 11 s failure: 5.4 + 11 + 2 + 1 = 19.4 s when the next connect takes 1 s, over 20 s when it is slower. Measure connect times on the first real POS. - Two lost queries in a row, or a lost
trxpagoanswer followed by a lost first query (about 24 s with 564 = 2): over the budget with any setting. Over 20 s the gateway may cancel the charge as for a POS that went away (ADR-003); a query that arrives before its next check prevents it. A cancelled sale is denied and the cashier retries. If the payer had already paid, the cancel is refused, the attempt ends PAID_UNCONFIRMED with a cockpit alert, and the POS's next query getsPAGO_APROBADO(AC-14, AC-26). Do not raise key 497 or key 498 without recomputing.
- Answer lost (the gateway got the query):
- [ ] POS build with changes 1 to 5 (SPEC section 2): S4 POS repository (
20261117_CYRE_S4_PagoQRMunic) commitc3ef254or later. Build withco.batand ship its whole output,POS_MAIN.EXEand everyPOS_*.DLL(17 files forc3ef254), together. Record the SHA-256 of every file you ship in the change record and keep a copy of that exact set.docs/evidence/2026-11-18/pos_build.txtlists the set that was tested on the bench; a rebuild, even ofc3ef254, gives other hashes (the binaries embed source file times). Change 1 adds exports toPOS_MAIN.EXE, which shifts its export ordinals, and the DLLs import from it by ordinal: an old DLL next to the new EXE (or the reverse) calls the wrong functions, the fiscal close included. Never ship the binaries committed undersrcs/in the S4 repository: they are the pre-change baseline. - QR render: when a response (
trxpagoortrxes) carriesqrdataand no QR is on screen, the POS draws it. - Poll interval from key 564.
- Esc cancel (only with key 543 non-zero): the cashier presses Esc while waiting and enters the cashier password; the
POS then sends
trxanulacionfor the pending id; if the cancel is not approved, the POS runs one last query and acceptsPAGO_APROBADOas an approved payment. - Resend
trxpago: if no QR is on screen after 2 queries, the POS resends the sametrxpago(sameid), at most 3 times; the gateway never makes a second charge for the same id (C4). - Short
trxpagowait: the wait for thetrxpagoanswer is capped at 10 s in the build (not a profile key); the POS logs show it ends about 11 s after thetrxpagois sent, and the first query follows at once, without the key 564 pause. A lost answer is then recovered (the query brings the QR) before the 20 s rule. Without it a lost answer always ends in a denied sale. - [ ] POS points at the gateway URL (
http://<server.address>:8080),medio de pagoconfigured, cashback disabled for this method (cashback > 0 is rejected). - [ ] One end-to-end test payment per new POS against a SANDBOX merchant before it takes real payments, including one Esc cancel (proves key 543).
What the cashier sees (texts as the POS displays them; / separates the lines of one message box)
| Situation | On the POS | What to do |
|---|---|---|
| Waiting for the customer | The QR and "Escanee el QR con la Billetera Municipal - Si no puede pagar presione Esc". | Key 543 = 1: Esc shows "Aviso: Cajero interrumpio proceso de autorizacion!" and "Ingrese clave Cajero actual!": the cashier enters the cashier password (it asks again until it is right), then "Anulando PAGO-QR Id:N". Key 543 = 0: Esc does nothing; wait. |
| Paid | "Aviso: PAGO-QR OK" | The sale closes. |
| Cancelled by Esc | "Aviso: PAGO-QR anulado" | Nothing was charged. Charge again in another way or with a new QR. |
| QR expired / cancelled / rejected | "Autorizando PAGO-QR / Importe:... / Resultado: Denegado / |
Safe to charge again, unless the reason contains "NO cobrar de nuevo" (rule below). |
| Time limit reached | "No se pudo completar PAGO QR / Reintenta via Consulta del PAGO?" (OK or cancel button) | OK: one more query on the same id; while the charge is still pending the question comes back right away: press OK again while the customer is paying (a late payment is recovered). Cancel asks "Confirma Cancelacion de Consulta PAGOQR?": OK there cancels the pending charge and makes one final query, exactly like Esc (this works even with key 543 = 0); cancel goes back to querying. |
| Final query without an answer (after Esc or the cancel) | "No se pudo consultar el PAGO QR / El pago podria estar acreditado / Reintenta consulta?" | OK (retry). Cancel ends with "Sin respuesta: verificar el pago antes de cobrar de nuevo" (rule below). |
Cashier rule (print and post at the till; one-page Spanish sheet: docs/cajero-billetera-municipal.md). The customer
may already have paid, so do not charge again, with this or any other method, until the payment is verified in the
cockpit (sections 7.1 and 7.2: escalate with the ticket and the attempt number Id:N) when the POS shows:
- any "Resultado: NO aprobado" after Esc or a cancel, whatever reason follows it, in particular:
Sin respuesta: verificar el pago antes de cobrar de nuevo(the final query got no answer);Anulacion no confirmada(no reason received);Outcome unknown: try again in a few secondsandThe cancellation was not confirmed: try again(the gateway could not confirm the cancel with the Municipality);Pago ya acreditado: pedir devolución a la Muni(the payment was credited and cannot be cancelled from the POS: the customer has paid; if the sale must be undone, ask the Municipality for the refund);- any reason that contains "NO cobrar de nuevo", after Esc or not:
Monto acreditado distinto: NO cobrar de nuevo, verificar en cockpit(AMOUNT_MISMATCH: the customer paid, for another amount);Cerrado por admin: NO cobrar de nuevo, verificar con la Muni(CLOSED_BY_ADMIN: an administrator closed a stuck attempt).
7. Operations
Cockpit: GW/admin/. Menu: Comercios, Intentos, Alertas, Tiempos, Usuarios, Mi contraseña. Every cockpit action is recorded
in the append-only audit table.
7.1 Alerts ("Alertas")
An alert stays open until an admin resolves it ("Resolver alerta" + note, recorded as an event). Held and stuck alerts are raised once per episode. Always check the attempt detail ("Intentos" > the attempt > "Eventos") first.
| Alert (cockpit label) | Meaning | What to do |
|---|---|---|
PAID_UNCONFIRMED ("Pagado sin confirmar") |
The customer paid after the POS gave up (abandoned or timed out). The charge is credited. | Do not charge again. Ask the cashier to retry the sale with "Reintenta via Consulta" on the same attempt: the POS then receives the approval. If the sale cannot be recovered at the POS, handle it manually with the Municipality (refund or record the sale by hand). Resolve with a note saying which. |
MUNI_UNAUTHORIZED ("Municipalidad: no autorizado (401)") |
The municipal API refused the merchant's API key: wrong, revoked or typed for the other environment. Payments of that merchant fail. | Check the merchant's "Ambiente" and ask the Municipality for the current key; rotate it (7.4). Make a SANDBOX test (section 5). Resolve with a note. |
AMOUNT_MISMATCH ("Monto acreditado distinto") |
The municipal API credited an amount different from the sale (or unreadable). The POS got the "NO cobrar de nuevo" denial. | The customer paid: do not charge again. Compare the attempt amount with the credited amount at the Municipality; arrange the difference (refund or collect the rest) with the cashier and the Municipality. Resolve with a note. |
MUNI_STUCK ("Consulta municipal trabada") |
The municipal API kept refusing the queries or cancels of one attempt (12 in a row); the gateway now asks only every 300 s. The outcome is unknown. | Check the municipal service status and ask the Municipality what happened to the charge. When the municipal API answers again the attempt settles by itself. If it stays blocked past its expiry, close it (7.3). |
ENVIRONMENT_MISMATCH ("Ambiente distinto") |
The merchant's environment or CUIT changed while an attempt was in flight, so the attempt is held (C6): it is never sent with the other environment's key. | Do not change a merchant's environment or CUIT with payments in flight (the cockpit refuses most cases). Verify the attempt's outcome with the Municipality, then close the held attempt after its expiry (7.3). |
7.2 Denials that say "NO cobrar de nuevo", and unconfirmed cancels
"NO cobrar de nuevo" comes from AMOUNT_MISMATCH or CLOSED_BY_ADMIN attempts. A cashier also escalates every "Resultado: NO
aprobado" after Esc or a cancel (the reasons are listed in the cashier rule, section 6). Open the attempt in "Intentos"
(the Id:N on the POS is the attempt number), read the timeline, and phone the Municipality before telling the cashier
anything. The customer may have been charged.
POS restarted in the middle of a sale (RISKS R-09). After a restart the POS can reopen the ticket with its items but without a PAGO QR line that was already paid, and ask for the money again. When a cashier reports a restart during a sale, or the payer says they already paid:
- In "Intentos", set "Desde" and "Hasta" to today, choose "Comercio", then "Sucursal", and type the POS number in "Caja (POS)".
- Set "Estado" to "Pagado", then search again with "Pagado sin confirmar" (the filter takes one status at a time).
- Look for an attempt whose "Monto" is the amount of the QR payment the cashier or payer describes. That is the PAGO QR
line, not the ticket total, which can include other payments. Open it: "Fecha de pago" must be shortly before the
restart or the payer's claim. The "Intento" number is the
Id:Nthe POS shows. - The cockpit cannot tie an attempt to a ticket, and amounts repeat. Ask the cashier which tickets that POS closed since the payment. Tell the cashier not to collect the amount again only when exactly one attempt fits and no closed ticket accounts for it. Otherwise phone the Municipality before deciding.
- A paid attempt has no note field in the cockpit. Record the decision (attempt number, POS, ticket, amount, what was decided) in the operator's incident log. How the restored ticket is closed at the POS is not verified yet.
7.3 Close a held or stuck attempt (D7)
For an attempt that is held (merchant mismatch) or stuck (MUNI_STUCK), after its expira plus the grace period:
- [ ] Verify with the Municipality whether the charge was paid.
- [ ] "Intentos" > the attempt > "Cerrar intento trabado" (section "Cierre manual"). The button is disabled, with the reason shown, until the attempt is eligible.
- [ ] Enter your current password and a mandatory note ("Nota (obligatoria)"). The attempt ends
Cerrado por admin, an audit entry and an attempt event are appended, and the POS gets the "NO cobrar de nuevo" denial.
7.4 Rotate a merchant API key
- [ ] "Comercios" > the merchant > "Rotar clave de API": your current password and the new key. The screen shows the environment the key is for ("Ambiente de la clave"); a key for the wrong environment is refused later by the Municipality (401).
- [ ] The old key stops being used at once, the new one is never shown again. Smoke-test a SANDBOX merchant afterwards.
- [ ] Editing a merchant, activating or deactivating it also asks for your password. Deactivating only stops new
trxids; payments in flight keep being polled.
7.5 User management ("Usuarios")
- [ ] "Nuevo usuario": username, your current password, the new user's password (12+ characters). Every user is an ADMIN (there is no partial role in v1).
- [ ] "Restablecer contraseña" resets another user's password; "Deshabilitar" / "Habilitar" disables or enables a user. A reset or disable ends that user's other sessions. Each user changes their own under "Mi contraseña".
- [ ] 5 wrong passwords lock a user for 15 minutes (wrong "current password" confirmations count too). Wait, or have another admin reset the password.
- [ ] Keep at least two enabled admins. If an admin is locked out, another admin resets the password. With no other enabled admin, the installer (4.2) is the way back in, but it refuses while an enabled ADMIN exists.
- [ ] The only admin forgot the password (or left): as a SQL Server administrator, disable that user, then create a new admin with the installer. The username must be new (usernames are unique). This SQL change bypasses the cockpit audit: write it in the operations log, and have the new admin reset or keep disabled the old user from the cockpit.
USE [GatewayQRMunic];
UPDATE dbo.admin_user SET enabled = 0, credentials_version = credentials_version + 1, updated_at = SYSUTCDATETIME()
WHERE username = N'<lost admin>' AND role = 'ADMIN';
Then run 4.2 with --gqrm.admin.bootstrap.username=<new name>.
8. Upgrade and rollback
Why a restore needs care. The attempt number (trxid, the IDENTITY of dbo.payment_attempt) is part of
referenciaExterna = {branch}-{pos}-{trxid}, the municipal idempotency key, and the POS asks GET /api/trxes/{id} by it. A
restore rewinds the numbering, so the gateway would hand out numbers already used after the back-up: a new sale could be
attached to an older municipal charge (possibly already PAID) and a POS could read another till's attempt. Every restore
therefore records the last number before restoring and re-seeds above it before the gateway starts (8.2).
8.1 Upgrade (off-hours; every POS idle, no cashier mid-payment)
- [ ] Build and check the new release (4.1). Read its migrations: they are forward-only.
- [ ] Stop first, so no attempt is created after the back-up:
nssm stop GatewayQRMunic. - [ ] Record the last attempt number and the current UTC time in the change record ("trxid at back-up", "back-up time
UTC"), then back up (
COPY_ONLYkeeps the scheduled back-up chain intact). Every back-up file gets its own name (running version and date/time):INIToverwrites a file of the same name, which would destroy the previous rollback point. Write the file name in the change record:
USE [GatewayQRMunic];
SELECT IDENT_CURRENT('dbo.payment_attempt') AS trxid_at_backup, SYSUTCDATETIME() AS backup_time_utc;
BACKUP DATABASE [GatewayQRMunic] TO DISK = N'D:\Backups\GatewayQRMunic_pre-upgrade_<running version>_<yyyyMMdd-HHmm>.bak' WITH COPY_ONLY, CHECKSUM, INIT;
- [ ] Keep the running jar: rename
gatewayqrmunic.jartogatewayqrmunic.jar.previous. - [ ] If you removed
db_ddladminafter the install, add it back for this start. - [ ]
nssm get GatewayQRMunic AppParametersstarts with-XX:-UseBASE64Intrinsics; if not, apply "Existing service" (end of section 4.3) after this upgrade. - [ ] Copy the new jar as
gatewayqrmunic.jar,nssm start GatewayQRMunic. Flyway applies the pending migrations; watchlogs\gateway.err.logandlogs\gateway.out.logfor "Started". If a migration fails, follow 4.4. - [ ] Run the smoke test (section 5) and open "Alertas".
- [ ] Optionally drop
db_ddladminagain.
8.2 Rollback and every restore of the database
Flyway is forward-only: the previous jar cannot run on a newer schema, so a rollback restores the back-up. The same steps apply to a restore after a failed migration (4.4) and to any other restore.
- Stop the service:
nssm stop GatewayQRMunic(a gateway that fails on start is restarted every 10 s by NSSM). Keep every POS idle (no Billetera Municipal sales) until step 7 is done. - Record, from the live database, before restoring:
USE [GatewayQRMunic];
SELECT IDENT_CURRENT('dbo.payment_attempt') AS last_trxid;
-- attempts created OR changed after the back-up: keep this output, it is the only local record of them.
-- a) the back-up comes from 8.1: use the "trxid at back-up" and the "back-up time UTC" of the change record
SELECT trxid, referencia_externa, status, amount, id_cobro, created_at, updated_at
FROM dbo.payment_attempt
WHERE trxid > <trxid at back-up> OR updated_at >= '<back-up time UTC>'
OR cancel_requested_at >= '<back-up time UTC>' OR last_create_sent_at >= '<back-up time UTC>'
ORDER BY trxid;
-- b) any other back-up: the cut-off is the back-up's start time, in UTC (see below)
SELECT trxid, referencia_externa, status, amount, id_cobro, created_at, updated_at
FROM dbo.payment_attempt
WHERE created_at >= '<cutoff_utc>' OR updated_at >= '<cutoff_utc>'
OR cancel_requested_at >= '<cutoff_utc>' OR last_create_sent_at >= '<cutoff_utc>'
ORDER BY trxid;
An attempt that already existed at the back-up and changed afterwards (paid, cancelled, expired) comes back in its old
state, so it is listed too. Every time column is UTC (DATETIME2, no zone, written by the gateway in UTC):
updated_at is set on every status change of an attempt; a cancel request or a resent charge without a status change
only sets cancel_requested_at / last_create_sent_at, hence the extra conditions.
For b), read the cut-off from the back-up file itself. A file can hold several back-up sets: RESTORE HEADERONLY
lists one row per set. Take the row of the set you will restore (BackupTypeDescription = Database; normally the
latest BackupStartDate) and write down its Position: step 4 restores that set (WITH FILE = <Position>; without it
SQL Server restores position 1). BackupStartDate is the local time of the server that took the back-up, while the
attempt columns are UTC, so convert it with that server's Windows time zone (tzutil /g on it, for example
Argentina Standard Time):
RESTORE HEADERONLY FROM DISK = N'<back-up file to restore>'; -- one row per set: read Position and BackupStartDate
SELECT CONVERT(datetime2(3), CAST('<BackupStartDate, yyyy-mm-dd hh:mi:ss>' AS datetime2(3))
AT TIME ZONE N'<Windows time zone of that server>' AT TIME ZONE N'UTC') AS cutoff_utc;
An earlier cut-off only lists more attempts (attempts already in the back-up show up too), which is safe; a later one loses attempts. When unsure of the zone, go some hours earlier.
- Decision gate: if that query returns any row (the new version created or changed an attempt after the back-up), prefer a forward fix (a corrected release, no restore): a restore loses those changes locally. Restore only if a forward fix is not possible, and then step 7 is mandatory.
- Back up the live database first, then restore.
RESTORE ... WITH REPLACEdestroys every row written after the back-up, not only attempts: theattempt_eventtimeline (C7),alert,wire_logandadmin_audit. The pre-rollback back-up below is the only copy of them: write a new file (never the one you restore; version and date/time in the name) and keep it with the change record. The restore file is the 8.1 back-up of the change record for a rollback, or the back-up chosen for any other restore. Run the back-up on its own and go on only when it ends with "BACKUP DATABASE successfully processed" and theVERIFYONLYsays the back-up set is valid (a failed back-up followed by the restore would lose those rows for good). If the live database cannot be backed up at all (damaged or lost), this is the disaster-recovery case at the end of this section:
USE master;
BACKUP DATABASE [GatewayQRMunic] TO DISK = N'D:\Backups\GatewayQRMunic_pre-rollback_<running version>_<yyyyMMdd-HHmm>.bak' WITH COPY_ONLY, CHECKSUM, INIT;
RESTORE VERIFYONLY FROM DISK = N'D:\Backups\GatewayQRMunic_pre-rollback_<running version>_<yyyyMMdd-HHmm>.bak' WITH FILE = 1, CHECKSUM;
Then pick the set to restore: the file may hold several sets (one row each in RESTORE HEADERONLY). Use the
Position of the row with BackupTypeDescription = Database that you chose (for b) in step 2, the row of the
cut-off; an 8.1 file written with INIT has one set, position 1), check it, and restore that set:
USE master;
RESTORE HEADERONLY FROM DISK = N'<back-up file to restore>'; -- Position, BackupTypeDescription, BackupStartDate
RESTORE VERIFYONLY FROM DISK = N'<back-up file to restore>' WITH FILE = <Position>;
USE master;
ALTER DATABASE [GatewayQRMunic] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
RESTORE DATABASE [GatewayQRMunic] FROM DISK = N'<back-up file to restore>' WITH FILE = <Position>, REPLACE;
ALTER DATABASE [GatewayQRMunic] SET MULTI_USER;
Restored on another SQL Server instance: the data and log paths stored in the back-up may not exist there. List the
files of the set and move each one to a folder of that instance. If the database does not exist there yet, leave out
the two ALTER DATABASE lines (they fail on a missing database):
USE master;
RESTORE FILELISTONLY FROM DISK = N'<back-up file to restore>' WITH FILE = <Position>; -- LogicalName, Type (D data, L log)
RESTORE DATABASE [GatewayQRMunic] FROM DISK = N'<back-up file to restore>' WITH FILE = <Position>, REPLACE,
MOVE N'<LogicalName of the D row>' TO N'<data folder of that instance>\GatewayQRMunic.mdf',
MOVE N'<LogicalName of the L row>' TO N'<log folder of that instance>\GatewayQRMunic_log.ldf';
Then, on another instance (or when the login was dropped and created again): the database user <app user> (the
GQRM_APP_USER of section 2, gqrm_app by default) is orphaned (its SID does not match the login) and the gateway
cannot log in. If the login exists on that instance, map it again. If it does not, run section 2 now, after the
restore (it creates the login and maps the restored user to it; run before the restore it would only create a
database that the restore replaces), with the same password, taken from the vault: section 2 sets the login's
password, and the gqrm.db.password in the config must keep matching it.
USE [GatewayQRMunic];
ALTER USER [<app user>] WITH LOGIN = [<app user>];
- Re-seed the attempt numbering before any start (the next attempt gets the value + 1). Use
last_trxidfrom step 2 plus a margin, for example 1000. The value must stay below 2147483647: the DOS POS stores the attempt id as a 32-bitlong.
USE [GatewayQRMunic];
DBCC CHECKIDENT ('dbo.payment_attempt', RESEED, <last_trxid + 1000>);
DBCC CHECKIDENT ('dbo.payment_attempt', NORESEED); -- shows the current value: it must be the one just set
- Put the matching jar back (
gatewayqrmunic.jar.previousasgatewayqrmunic.jarfor a rollback);nssm start GatewayQRMunic; run the smoke test. - Reconcile with the Municipality every attempt of the step 2 list (by
referencia_externa) and every municipal movement from the cut-off on (the "back-up time UTC" of 8.1, or the cut-off of step 2 b), whatever the day): a payment made after the back-up is missing locally or shows in its old state (refund it or record the sale by hand). Only then let the POS take Billetera Municipal sales again.
Disaster recovery (the live database is lost, so step 2 cannot be read): restore the latest back-up as in step 4
(choose the set by its Position and restore it WITH FILE = <Position>; WITH MOVE and the user mapping on another
instance) and re-seed above
every attempt number ever issued: take the highest idTrx from the POS PAGOQR logs or the last part of the highest
referenciaExterna in the Municipality's movements, and add a large margin (for example 100000; still below 2147483647).
Then steps 5 to 7, reconciling from the back-up time on.
9. Logs and secrets
- Service logs:
C:\GatewayQRMunic\logs\gateway.out.logandgateway.err.log(NSSM, rotated at 10 MB). Application log level is the Spring default (INFO). - Database records:
wire_log(every municipal call, masked before it is stored, kept 90 days, purged hourly),attempt_event(append-only timeline),admin_audit(append-only cockpit actions). - Never logged and never shown (tested): the merchant API key (C2: encrypted at rest, the
X-Api-Keyheader is masked in the wire log, never sent to the POS or the cockpit), the payer's employee numberpagadoPorLegajo(C3: database only, Ley 25.326), the master key, the database password, and any admin password (stored only as a BCrypt hash). - A heap dump or a memory capture of the running process would hold the master key and the decrypted keys: never take or share one from production.
10. Dev bench and BootUI (development only, never in production)
- Muni emulator bench (ADR-004): the
muni-emulatormodule is a local stand-in for the municipal API with fault knobs, used to tune the gateway before connecting the real POS. Run it locally (default port 9191) and point a development gateway'smuni.sandbox-base-urlat it, and itsgqrm.db.nameat a development database such asGatewayQRMunic_DEV. Seed that database withdb/seed/seed-dev.sql. It refuses without-v ALLOW_DEV_SEED=1, on any database whose name does not end in_DEV,_QAor_IT(the production nameGatewayQRMunicincluded), on a name that containsprod,prdorlive, and on a database with PRODUCTION data. It creates the inactive SANDBOX merchantDEV-SANDBOXwith branch 1 and no key and no admin: set the key in the cockpit and activate it. The SQL credentials go through theSQLCMDUSER/SQLCMDPASSWORDenvironment variables, never-P(or use Windows authentication,-E):
$env:SQLCMDUSER = '<dev login>'; $s = Read-Host -AsSecureString 'Password'
try {
$env:SQLCMDPASSWORD = [System.Net.NetworkCredential]::new('', $s).Password
sqlcmd -S localhost -d GatewayQRMunic_DEV -C -I -b -v ALLOW_DEV_SEED=1 -i db/seed/seed-dev.sql
} finally { Remove-Item Env:SQLCMDPASSWORD, Env:SQLCMDUSER -ErrorAction SilentlyContinue }
Never deploy the emulator to a CYRE server.
- BootUI (ADR-002): a developer console at /bootui, enabled only by mvn -Pbootui with the Spring profile local. It shows
HTTP exchanges, SQL, environment and heap dumps. It must never reach a release: build releases with mvn clean and no
-Pbootui, and verify the jar (4.1). The prod profile refuses to start a jar that contains it.