// Copyright (c) 2021. Huawei Technologies Co., Ltd. All rights reserved.

// Package common this file common validators
package common

import (
"crypto/tls"
"errors"
"net"
"regexp"
"time"

"huawei.com/npu-exporter/hwlog"
"huawei.com/npu-exporter/utils"

"huawei.com/mindxdl/base/common/constants"
)

const (
portLowerLimit = 1025
portUpperLimit = 40000
nameMaxLength = 63
nameMinLength = 3
serviceLogMaxSize = 200
nameFormat = `^[a-z0-9]+[a-z0-9-]*[a-z0-9]+$`
)

// ServerParam ServerParam
type ServerParam struct {
IP string
Port int
Version bool
Concurrency int
MaxConcurrency int
EnableHTTP bool
EncryptAlgorithm int
TLSSuites int
CipherSuites []uint16
AuthMode string
OverdueTime int
CheckCertPeriod time.Duration
DNSName string
DirName string
ReadTimeOut time.Duration
WriteTimeOut time.Duration
}

// GetDefaultServiceParam get default service param
func GetDefaultServiceParam() *ServerParam {
return &ServerParam{
MaxConcurrency: MaxConcurrency,
CheckCertPeriod: time.Hour,
AuthMode: TwoWay,
OverdueTime: utils.OverdueTime,
ReadTimeOut: HTTPServerTimeout,
WriteTimeOut: HTTPServerTimeout,
}
}

// WebParamValid doing param check
func WebParamValid(sp *ServerParam) error {
if sp.Port < portLowerLimit || sp.Port > portUpperLimit {
return errors.New("the port is invalid")
}
parsedIP := net.ParseIP(sp.IP)
if parsedIP == nil {
return errors.New("the listen ip is invalid")
}
sp.IP = parsedIP.String()
hwlog.RunLog.Infof("listen on: %s", sp.IP)

return nil
}

// ParseTLSParams ParseTLSParams
func ParseTLSParams(sp *ServerParam) {
if sp.EncryptAlgorithm != utils.Aes128gcm && sp.EncryptAlgorithm != utils.Aes256gcm {
hwlog.RunLog.Warn("reset invalid encryptAlgorithm = 9")
sp.EncryptAlgorithm = utils.Aes256gcm
}
if sp.TLSSuites != 0 && sp.TLSSuites != 1 {
hwlog.RunLog.Warn("reset invalid tlsSuites = 1")
sp.TLSSuites = 1
}
if sp.TLSSuites == 0 {
sp.CipherSuites = []uint16{tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}
} else {
sp.CipherSuites = []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}
}
}

// ValidName valid pod name or namespace
func ValidName(nameType, name string, b BaseCtx) bool {
if name == "" {
hwlog.RunLog.ErrorfWithCtx(b.Ctx, "%s is empty.", nameType)
return false
}
array := []rune(name)
if len(array) > nameMaxLength || len(array) < nameMinLength {
hwlog.RunLog.ErrorfWithCtx(b.Ctx, "%s length (%v) invalid.", nameType, len(array))
return false
}
var reg = regexp.MustCompile(nameFormat)
ok := reg.MatchString(name)
if !ok {
hwlog.RunLog.ErrorfWithCtx(b.Ctx, "%s is not meet requirement.", nameType)
return false
}
return true
}

func validLogLimitOffset(logOffset, logLimit uint64) error {
if logLimit > serviceLogMaxSize {
return errors.New("too large of limit")
}
if logOffset < 0 {
return errors.New("offset is less than 0")
}
return nil
}

// CheckString check string
func CheckString(passString string) error {
if matched, err := regexp.MatchString(constants.PassRegex, passString); err != nil || !matched {
return errors.New("password MatchString failed")
}

complexCheckRegexArr := []string{
constants.LowercaseCharactersRegex,
constants.UppercaseCharactersRegex,
constants.BaseNumberRegex,
constants.SpecialCharactersRegex,
}
complexCount := 0
for _, pattern := range complexCheckRegexArr {
if matched, err := regexp.MatchString(pattern, passString); matched && err == nil {
complexCount++
}
}
if complexCount < constants.MinComplexCount {
return errors.New("password complexCheck failed")
}
return nil
}

mindxdl--common--validators.go的更多相关文章

  1. RoR - More Active Record

    Active Record Scope: default_scope:   默认的检索方式 #Use unscoped to break out of the default class Hobby ...

  2. Yii2在Form中处理短信验证码的Validator,耦合度最低的短信验证码验证方式

    短信验证码在目前大多数web应用中都会有,本文介绍一个基于Yii2 Validator方式的验证码验证方式. 在其他文章中看到的方式大多比较难做到一次封装,多次重用. 使用此方式的好处自然不用多说,V ...

  3. ASP.NET - Validators

    ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated, or ...

  4. Socket聊天程序——Common

    写在前面: 上一篇记录了Socket聊天程序的客户端设计,为了记录的完整性,这里还是将Socket聊天的最后一个模块--Common模块记录一下.Common的设计如下: 功能说明: Common模块 ...

  5. angularjs 1 开发简单案例(包含common.js,service.js,controller.js,page)

    common.js var app = angular.module('app', ['ngFileUpload']) .factory('SV_Common', function ($http) { ...

  6. Common Bugs in C Programming

    There are some Common Bugs in C Programming. Most of the contents are directly from or modified from ...

  7. ANSI Common Lisp Practice - My Answers - Chatper - 3

    Ok, Go ahead. 1 (a) (b) (c) (d) 2 注:union 在 Common Lisp 中的作用就是求两个集合的并集.但是这有一个前提,即给的两个列表已经满足集合的属性了.具体 ...

  8. [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

  9. [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  10. [LeetCode] Longest Common Prefix 最长共同前缀

    Write a function to find the longest common prefix string amongst an array of strings. 这道题让我们求一系列字符串 ...

随机推荐

  1. 经纬度转换为距离单位km的方法

    function rad(d){ return d * Math.PI /180.0; }; GetDistance(lat1, lng1, lat2, lng2){ var radLat1 =rad ...

  2. KingbaseES行转列(PIVOT)

    如果以交叉表格式显示,则商业智能查询返回的数据通常是最有用的.SELECT语句的pivot_.数据透视是数据仓库中的一项关键技术.在其中,您可以将多行输入转换为数据仓库中较少且通常较宽的行.进行数据透 ...

  3. java的URI和URL的关系

    java的URI和URL到底是什么 在我们做开发时,经常有URI和URL弄混的问题,如果当时直接看URI和URL的源码就不可能弄混.首先我总结一下URI和URL的关系:他们的关系是:URL是一种特殊的 ...

  4. flutter系列之:flutter中常用的ListView layout详解

    目录 简介 ListView详解 ListView中的特有属性 ListView的构造函数 ListView的使用 总结 简介 ListView是包含多个child组件的widget,在ListVie ...

  5. Linux 使用 Systemd 管理进程服务

    转载自:https://mp.weixin.qq.com/s/e-_PUNolUm22-Uy_ZjpuEA systemd 介绍 systemd是目前Linux系统上主要的系统守护进程管理工具,由于i ...

  6. K8S ingress控制器

    文章转载自: K8S ingress控制器 (一)https://blog.51cto.com/u_13760351/2728917 K8S ingress控制器 (二)https://blog.51 ...

  7. Elasticsearch方案选型必须了解的10件事!

    文章转载自: https://mp.weixin.qq.com/s?__biz=MzI2NDY1MTA3OQ==&mid=2247484372&idx=1&sn=e863e46 ...

  8. 使用pip的方式安装docker-compose

    # 国内开启pip 下载加速:http://mirrors.aliyun.com/help/pypi mkdir ~/.pip/ cat > ~/.pip/pip.conf <<'E ...

  9. 监控elasticsearch

    转载自:https://cloud.tencent.com/developer/article/1655489 注意:上半截跟下半截是采用的不同的方式,建议采用下半截的方式,上半截的方式据说获取不到数 ...

  10. SonarQube 之 gitlab-plugin 配合 gitlab-ci 完成每次 commit 代码检测

    转载自:https://cloud.tencent.com/developer/article/1010601 1.背景介绍 我们知道使用 SonarQube 可以在日常开发中检测代码质量,除了使用 ...