001/*
002 * acme4j - Java ACME client
003 *
004 * Copyright (C) 2026 Richard "Shred" Körber
005 *   http://acme4j.shredzone.org
006 *
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
013 */
014package org.shredzone.acme4j.challenge;
015
016import static java.util.Objects.requireNonNull;
017
018import java.io.Serial;
019import java.net.URISyntaxException;
020import java.net.URL;
021import java.time.Instant;
022import java.util.ArrayList;
023import java.util.Collections;
024import java.util.List;
025
026import edu.umd.cs.findbugs.annotations.Nullable;
027import org.shredzone.acme4j.Identifier;
028import org.shredzone.acme4j.Login;
029import org.shredzone.acme4j.exception.AcmeProtocolException;
030import org.shredzone.acme4j.toolbox.AcmeUtils;
031import org.shredzone.acme4j.toolbox.JSON;
032
033/**
034 * Implements the {@value TYPE} challenge. It requires a specific DNS record for domain
035 * validation. See the acme4j documentation for a detailed explanation.
036 *
037 * @draft This class is currently based on an RFC draft. It may be changed or removed
038 * without notice to reflect future changes to the draft. SemVer rules do not apply here.
039 * @since 5.0.0
040 */
041public class DnsPersist01Challenge extends Challenge {
042    @Serial
043    private static final long serialVersionUID = 7532514098897449519L;
044
045    /**
046     * Challenge type name: {@value}
047     */
048    public static final String TYPE = "dns-persist-01";
049
050    protected static final String KEY_ISSUER_DOMAIN_NAMES = "issuer-domain-names";
051    protected static final String RECORD_NAME_PREFIX = "_validation-persist";
052    protected static final String KEY_ACCOUNT_URI = "accounturi";
053
054    private static final int ISSUER_SIZE_LIMIT = 10;        // according to the specs
055    private static final int DOMAIN_LENGTH_LIMIT = 253;     // according to the specs
056
057    private @Nullable List<String> issuerDomainNames;
058
059    /**
060     * Creates a new generic {@link DnsPersist01Challenge} object.
061     *
062     * @param login
063     *         {@link Login} the resource is bound with
064     * @param data
065     *         {@link JSON} challenge data
066     */
067    public DnsPersist01Challenge(Login login, JSON data) {
068        super(login, data);
069    }
070
071    /**
072     * Returns the list of issuer-domain-names from the CA. The list is guaranteed to
073     * have at least one element.
074     */
075    public List<String> getIssuerDomainNames() {
076        if (issuerDomainNames == null) {
077            var domainNames = getJSON().get(KEY_ISSUER_DOMAIN_NAMES).asArray().stream()
078                    .map(JSON.Value::asString)
079                    .map(AcmeUtils::toAce)
080                    .toList();
081
082            if (domainNames.isEmpty()) {
083                // malform check is mandatory according to the specification
084                throw new AcmeProtocolException("issuer-domain-names missing or empty");
085            }
086
087            if (domainNames.size() > ISSUER_SIZE_LIMIT) {
088                // malform check is mandatory according to the specification
089                throw new AcmeProtocolException("issuer-domain-names size limit exceeded: "
090                        + domainNames.size() + " > " + ISSUER_SIZE_LIMIT);
091            }
092
093            if (domainNames.stream().anyMatch(it -> it.endsWith("."))) {
094                throw new AcmeProtocolException("issuer-domain-names must not have trailing dots");
095            }
096
097            if (!domainNames.stream().allMatch(it -> it.length() <= DOMAIN_LENGTH_LIMIT)) {
098                throw new AcmeProtocolException("issuer-domain-names content too long");
099            }
100
101            issuerDomainNames = domainNames;
102        }
103        return Collections.unmodifiableList(issuerDomainNames);
104    }
105
106    /**
107     * Converts a domain identifier to the Resource Record name to be used for the DNS TXT
108     * record.
109     *
110     * @param identifier
111     *         Domain {@link Identifier} of the domain to be validated
112     * @return Resource Record name (e.g. {@code _validation-persist.www.example.org.},
113     * note the trailing full stop character).
114     */
115    public String getRRName(Identifier identifier) {
116        return getRRName(identifier.getDomain());
117    }
118
119    /**
120     * Converts a domain identifier to the Resource Record name to be used for the DNS TXT
121     * record.
122     *
123     * @param domain
124     *         Domain name to be validated
125     * @return Resource Record name (e.g. {@code _validation-persist.www.example.org.},
126     * note the trailing full stop character).
127     */
128    public String getRRName(String domain) {
129        return RECORD_NAME_PREFIX + '.' + AcmeUtils.toAce(domain) + '.';
130    }
131
132    /**
133     * Returns a builder for the RDATA value of the DNS TXT record.
134     *
135     * @return Builder for the RDATA
136     */
137    public Builder buildRData() {
138        return new Builder(getLogin(), getIssuerDomainNames());
139    }
140
141    /**
142     * Convenience call to get a standard RDATA without optional tags.
143     *
144     * @return RRDATA
145     */
146    public String getRData() {
147        return buildRData().build();
148    }
149
150    /**
151     * Returns the Account URI that is expected to request the validation.
152     *
153     * @since 5.1.0
154     */
155    public URL getAccountUrl() {
156        return getJSON().get(KEY_ACCOUNT_URI).asURL();
157    }
158
159    @Override
160    protected void invalidate() {
161        super.invalidate();
162        issuerDomainNames = null;
163    }
164
165    @Override
166    protected boolean acceptable(String type) {
167        return TYPE.equals(type);
168    }
169
170    @Override
171    protected void setJSON(JSON json) {
172        super.setJSON(json);
173        // TODO: In a future release, KEY_ACCOUNT_URI is expected to be mandatory,
174        //   and this check will always apply!
175        if (getJSON().contains(KEY_ACCOUNT_URI)) {
176            try {
177                var expectedAccount = getJSON().get(KEY_ACCOUNT_URI).asURI();
178                var actualAccount = getLogin().getAccount().getLocation().toURI();
179                if (!actualAccount.equals(expectedAccount)) {
180                    throw new AcmeProtocolException("challenge is intended for a different account: " + expectedAccount);
181                }
182            } catch (URISyntaxException ex) {
183                throw new IllegalStateException("Account URL is not an URI?", ex);
184            }
185        }
186    }
187
188    /**
189     * Builder for RDATA.
190     * <p>
191     * The following default values are assumed unless overridden by one of the builder
192     * methods:
193     * <ul>
194     *     <li>The first issuer domain name from the list of issuer domain names is used</li>
195     *     <li>No wildcard domain</li>
196     *     <li>No persistence limit</li>
197     *     <li>Generate quote-enclosed strings</li>
198     * </ul>
199     */
200    public static class Builder {
201        private final Login login;
202        private final List<String> issuerDomainNames;
203        private String issuer;
204        private boolean wildcard = false;
205        private boolean quotes = true;
206        private @Nullable Instant persistUntil = null;
207
208        private Builder(Login login, List<String> issuerDomainNames) {
209            this.login = login;
210            this.issuerDomainNames = issuerDomainNames;
211            this.issuer = issuerDomainNames.get(0);
212        }
213
214        /**
215         * Change the issuer domain name.
216         *
217         * @param issuer
218         *         Issuer domain name, must be one of
219         *         {@link DnsPersist01Challenge#getIssuerDomainNames()}.
220         */
221        public Builder issuerDomainName(String issuer) {
222            requireNonNull(issuer, "issuer");
223            if (!issuerDomainNames.contains(issuer)) {
224                throw new IllegalArgumentException("Domain " + issuer + " is not in the list of issuer-domain-names");
225            }
226            this.issuer = issuer;
227            return this;
228        }
229
230        /**
231         * Request wildcard validation.
232         */
233        public Builder wildcard() {
234            wildcard = true;
235            return this;
236        }
237
238        /**
239         * Instant until this RDATA is valid. The CA must not use this record after that.
240         *
241         * @param instant
242         *         Persist until instant
243         */
244        public Builder persistUntil(Instant instant) {
245            persistUntil = requireNonNull(instant, "instant");
246            return this;
247        }
248
249        /**
250         * Do not use quote-enclosed strings. Proper formatting of the resulting RDATA
251         * must be done externally!
252         */
253        public Builder noQuotes() {
254            quotes = false;
255            return this;
256        }
257
258        /**
259         * Build the RDATA string for the DNS TXT record.
260         */
261        public String build() {
262            var parts = new ArrayList<String>();
263            parts.add(issuer);
264            parts.add("accounturi=" + login.getAccount().getLocation());
265
266            if (wildcard) {
267                parts.add("policy=wildcard");
268            }
269
270            if (persistUntil != null) {
271                parts.add("persistUntil=" + persistUntil.getEpochSecond());
272            }
273
274            if (quotes) {
275                // Quotes inside the parts should be escaped. However, we don't expect
276                // that any part contains qoutes.
277                return '"' + String.join(";\" \" ", parts) + '"';
278            } else {
279                return String.join("; ", parts);
280            }
281        }
282    }
283
284}