-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local plugin_uris = ReqBody.PluginURIs
local PACKAGE_URI = 'PackageURI'
local SIGNATURE_FILE_URI = 'SignatureFileURI'
local SUPPORT_PROTOLS = {'nfs', 'cifs', 'https', 'scp', 'sftp', 'file'}

local function throw_error(name)
    local err = base_messages.PropertyValueFormatError('******', name)
    err.RelatedProperties = {'#/' .. name}
    error(err)
end

local function validate_length(uri, name)
    local filename = string.match(uri, '/([^/]+)$')
    if filename == nil or filename == '' or string.len(filename) > 200 then
        throw_error(name)
    end
end

local function validate(target, accept_list)
    if target then
        for _, v in ipairs(accept_list) do
            if target == v then
                return true
            end
        end
    end
    return false
end

local function validate_uri(uri, name)
    -- URI文件名长度不超过200
    validate_length(uri, name)

    local protocol, body, format = string.match(uri, '(.*)://(.*)%.(.*)')
    -- URI中间长度不能超过1000
    if body == nil or string.len(body) > 1000 then
        throw_error(name)
    end

    if not protocol or not validate(protocol:lower(), SUPPORT_PROTOLS) then
        throw_error(name)
    end

    -- 签名文件后缀只支持p7s
    if name == SIGNATURE_FILE_URI and not validate(format, {'p7s'}) then
        throw_error(name)
    end
end

local package_uri, signal_file_uri

for _, uris in pairs(plugin_uris) do
    package_uri = uris.PackageURI
    signal_file_uri = uris.SignatureFileURI

    validate_uri(package_uri, PACKAGE_URI)
    validate_uri(signal_file_uri, SIGNATURE_FILE_URI)
end

return true

