">
 

How to find expired signed URLs (S3, CloudFront, GCS) in your pages, emails and docs before customers hit AccessDenied

Iniciado por joomlamz, Hoje at 23:25

Respostas: 1   |   Visualizações: 1

Tópico anterior - Tópico seguinte

0 Membros e 2 Visitantes estão a ver este tópico.

Saudações à comunidade do **webmastersmz.com**. Como especialista em tecnologia, analisei o tópico sobre a expiração de *Signed URLs* (URLs assinados) e preparei um resumo técnico focado nos desafios reais que enfrentamos na gestão de infraestruturas em nuvem (S3, CloudFront, GCS).

### Análise Técnica: O Problema das "Signed URLs" Expiradas

O uso de *Signed URLs* é uma prática recomendada para garantir a segurança no acesso a ficheiros privados (como media, documentos ou backups). No entanto, o problema surge quando estas URLs são incorporadas em locais de "longa duração" — como bancos de dados de aplicações, históricos de e-mails, arquivos PDF ou documentos partilhados — sem um mecanismo de renovação automática. Quando o prazo de validade termina, o utilizador final recebe o erro `403 Access Denied`, resultando numa má experiência e num aumento desnecessário de tickets de suporte.

**Os pontos principais discutidos no tópico são:**

1.  **Auditoria de Conteúdo:** O desafio de localizar onde estas URLs estão espalhadas. A recomendação técnica é realizar uma varredura (crawl) periódica nos vossos *assets* de texto e bases de dados para identificar padrões de URLs de armazenamento em nuvem.
2.  **Estratégia de TTL (Time-to-Live):** É fundamental equilibrar a segurança com a conveniência. URLs com validade muito curta protegem melhor o conteúdo, mas aumentam a complexidade de gestão.
3.  **Abordagens de Correção:**
    *   **Proxying:** Em vez de expor a URL direta do S3, servir o ficheiro através de uma aplicação intermédia que valida a sessão do utilizador antes de gerar um novo link *on-the-fly*.
    *   **CloudFront Origin Access Control (OAC):** Utilizar políticas de acesso mais inteligentes para evitar que URLs assinadas sejam a única forma de autenticação.
    *   **Scripts de Monitorização:** Implementar cron-jobs que testam a validade das URLs armazenadas antes de estas serem servidas aos clientes.

**Questão para o debate:** Como é que vocês, gestores de sistemas em Moçambique, têm lidado com a gestão de *assets* privados? Preferem a complexidade das *Signed URLs* com expiração curta ou optam por soluções de *CDN* com autenticação via *token* ou *cookies*? Deixem as vossas experiências nos comentários para enriquecermos este tópico.

***

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com.

How to find expired signed URLs (S3, CloudFront, GCS) in your pages, emails and docs before customers hit AccessDenied



Tópico: How to find expired signed URLs (S3, CloudFront, GCS) in your pages, emails and docs before customers hit AccessDenied
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
Scheduled broken-link and redirect checks that tell you the moment a link breaks — linkbruno.com

A signed URL is a promise with a clock on it. You paste a presigned S3 link into a blog post, a docs page, a support article, or a "download the invoice" email template, it returns 200 today, and six days later it returns AccessDenied or Request has expired. A nightly link checker that only stores the status will report "fine" until the day after the expiry, which is also the day a customer clicks it.

You do not need to fetch the object to know when the promise ends. The expiry is in the query string. Parse it, compare it to now, and treat "already expired" and "expires within N days" as failures even if the URL is 200 this morning.



What the query string looks like


The common shapes:

•
S3 / AWS Signature V4: X-Amz-Date=20260315T120000Z and X-Amz-Expires=604800 (seconds). Expiry is the date plus the seconds. There is also X-Amz-Security-Token on temporary creds, which you should not log.

•
S3 Signature V2 (older): Expires=1773570000 (a Unix timestamp).

•
CloudFront: Expires=1773570000, or a Policy= (Base64) that contains an EpochTime. A canned policy uses Expires.

•
GCS: X-Goog-Date plus X-Goog-Expires (seconds), or sometimes Expires.

•
Azure Blob SAS: se=2026-03-15T12:00:00Z (and sp, sig, which you should not log).

If you cannot parse an expiry from a URL that has X-Amz-Signature, Signature, X-Goog-Signature or sig= in it, treat that as "unknown signed URL" and fail it or review it. A signed URL with no parseable expiry is not "fine"; it is a URL you do not understand.



A script that reports expiry, not the signature


import re
import sys
from datetime import datetime, timedelta, timezone
from urllib.parse import urlparse, parse_qs, unquote

WARN_WITHIN = timedelta(days=14)
NOW = datetime.now(timezone.utc)
# query keys we never print
SECRETS = re.compile(r"^(x-amz-signature|x-amz-security-token|signature|x-goog-signature|sig)$", re.I)

def redact(url):
p = urlparse(url)
q = parse_qs(p.query, keep_blank_values=True)
safe = "&".join(
f"{k}=..." if SECRETS.match(k) else f"{k}={v[0] if v else ''}"
for k, v in q.items()
)
return p._replace(query=safe).geturl()

def first(q, *keys):
for k in keys:
if k in q and q[k]:
return unquote(q[k][0])
return None

def parse_amz_date(value):
return datetime.strptime(value, "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc)

def expiry_of(url):
q = {k.lower(): v for k, v in parse_qs(urlparse(url).query).items()}
if first(q, "x-amz-date", "x-goog-date") and first(q, "x-amz-expires", "x-goog-expires"):
start = parse_amz_date(first(q, "x-amz-date", "x-goog-date"))
return start + timedelta(seconds=int(first(q, "x-amz-expires", "x-goog-expires")))
if first(q, "expires"):
raw = first(q, "expires")
if raw.isdigit():
return datetime.fromtimestamp(int(raw), timezone.utc)
return datetime.fromisoformat(raw.replace("Z", "+00:00"))
if first(q, "se"):  # Azure SAS
return datetime.fromisoformat(first(q, "se").replace("Z", "+00:00"))
keys = set(q)
if keys & {"x-amz-signature", "signature", "x-goog-signature", "sig", "policy"}:
return "UNKNOWN_SIGNED"
return None

for line in sys.stdin:
url = line.strip()
if not url:
continue
exp = expiry_of(url)
if exp is None:
continue
if exp == "UNKNOWN_SIGNED":
print(f"UNKNOWN_SIGNED\t{redact(url)}")
continue
if exp.tzinfo is None:
exp = exp.replace(tzinfo=timezone.utc)
remain = exp - NOW
if remain <= timedelta(0):
flag = "EXPIRED"
elif remain <= WARN_WITHIN:
flag = "EXPIRING"
else:
flag = "OK"
if flag != "OK":
print(f"{flag}\t{exp.isoformat()}\t{redact(url)}")

Feed it URLs, one per line: a crawl, a sitemap, a grep over the docs repo, the HTML of a week's email templates. It prints nothing for ordinary unsigned links, and it never prints the signature. That last part matters; a presigned URL is a credential, and CI logs are not a vault.

# example: extract hrefs from a built docs directory, then check
rg -oN "https?://[^\"')\s>]+" public/ | \
python3 signed_url_expiry.py



What to do with the ones it finds


Do not "fix" them by generating a new signed URL with a two-year expiry and pasting it back into the page. A long-lived signed URL is a long-lived key to that object, and it will still expire, just later, usually after you have forgotten it.

For a public object, drop the signature and use the object's public HTTPS URL (or a CloudFront URL that does not need a policy). If the object should be public, the link in a docs page should be public.

For a private object, do not put a signed URL into anything that is cached or archived (a blog post, a newsletter, a PDF, a GitHub README). Link to your app, and have the app mint a short-lived URL at click time. Emails that already went out cannot be rewritten; those objects need to stay where the old URL points, or you need a replacement path that does not depend on the old signature.

For CI, run the parser over the built site and over template fixtures. Fail the build on EXPIRED and on EXPIRING inside the window you chose. Fourteen days is a reasonable starting point for weekly-built docs; transactional email templates should probably fail if they contain any signed URL, because the template will outlive the signature.

A link can be 200 today and dead on a schedule you already printed in the query string. linkbruno.com checks published URLs on a schedule, so a download that has started returning AccessDenied does not wait for the first customer to complain.

Clock skew is the only common false positive: compare in UTC, and do not treat a URL that expires in 30 seconds as "fine" because it was 200 when the crawler started. And if you find a signed URL in a public git repo, rotate whatever keys could still be valid; the expiry in the query is for the object access, not a guarantee that the secret used to sign it is harmless.



Related reading


• Retiring an API version or a microservice? A 12-point checklist so every public URL and docs link keeps working

• How to check every link in your HTML email templates before they're sent (a Python script for CI)

• Case study (hypothetical): the 'View receipt' links in payment emails that expired after 7 days

• How to find broken links inside PDFs with Python (a script for a whole folder of whitepapers, manuals and invoices)

Have you found a signed URL that had already been sitting in a blog post or an email template past its expiry? Where was it, and what do you use instead now?


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: